iterate through Obejct from Firestore

Viewed 88

I am quite stuck. I have a Firestore Database with a collection of meals => than the type of meals => and then different maps with the specific information. (See screenshot).

With:

async function getMenu(){
        const items = [];
        try {
            setLoading(true)
            const querySnapshot = await getDocs(collection(db, "meals"));
            querySnapshot.forEach((doc) => {
                items.push(doc.data());
                console.log(doc.data());
            })
        } catch (error) {
            console.log(error)
        }
        setLoading(false);
        setMenus(items);
    }

    useEffect(() => {
        getMenu();
    },[]);

My console shows:

Object { "Currywurst Pommes": {…} } Object { "Hähnchen Salat": {…}, "Gemischter Salat": {…}, "Tomate-Mozarella": {…}, Beilagensalat: {…} }

Now I want to enter each Object and get the specific Information of every meal. How would I do that?

I am using React for my WebApp.

Thanks for the help in advance

Firestore

1 Answers

If you want to get all the detailed information like the property 'desc' of the food, you can do it like this:

async function getMenu(){
    const items = [];
    try {
        setLoading(true)
        const querySnapshot = await getDocs(collection(db, "meals"));
        querySnapshot.forEach((doc) => {
            items.push(doc.data());
            console.log(doc.data());

            var data = doc.data();
            Object.keys(data).forEach((key) => {
               var value = data[key];
               // handle data of element, like 'desc'
               console.log(value.desc);
            })
        })
    } catch (error) {
        console.log(error)
    }
    setLoading(false);
    setMenus(items);
}

useEffect(() => {
    getMenu();
},[]);
Related