'Get map key name and values stored on array from firestore

I'm trying to get the values from a map and store it in an array from firestore using react native. This is an example of how I would like the array to look, after the map gets pulled.

const [food, setFood] = useState([
    {Food: 'Cheese', Calories: 20, Quantity: 1, key: '1'},
    {Food: 'Lettuce', Calories: 10, Quantity: 1, key: '2'},

]);

Here is the stored data in firestore: firestore data

For getting the data and other fields from firestore I'm using this function:

const getFoodData = async () =>{

    const docRef = doc(db, "foods", uid);
    const docSnap = await getDoc(docRef);
    
    if (docSnap.exists()) {
      console.log("Document data:", docSnap.data());
    } else {
      console.log("No such document!");
    }
        setFood(docSnap.get("Food.Cheese.Calories"))
        console.log(food)
}

I'm able to get the value from an individual field by doing the above, but I need to have it stored in an array, like the first example. how would I be able to do that?



Solution 1:[1]

You can try using Object.keys() and then use a map as shown below:

const foodMap = docSnap.data().Food

const result = Object.keys(foodMap).map(key => ({ food: key, ...foodMap[key] }))

Solution 2:[2]

Great answer, Dharmaraj.

Adding code snippet so you can see it in action -

// Food is the result of doc.data().food
const food = {
  Cheese: { Calories: 20, Quantity: 1, key: '1'},
  Lettuce: { Calories: 10, Quantity: 1, key: '2'},
};

console.log('Firestore Data: ', food)

const result = Object.keys(food).map(key => ({ food: key, ...food[key]}))

console.log('Flattened result: ', result) 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharmaraj
Solution 2 Jake Cronin