Home > database >  Get documents name in Firestore and create nested object
Get documents name in Firestore and create nested object

Time:11-01

This question is related to this one: Get documents names in Firestore but I can't comment yet.

I am trying to get a nested object from my FireStore which looks like this

{"docname1": {…}, "docname2": {…}, "docname3": {…}}

I have this now but cant seem to figure out how to create the nested object to push it into the empty array.

 useEffect(() => {
    const getPlants = async () => {
        let response = []
        const querySnapshot = await firebase
            .firestore()
            .collection('plants')
            .get()
        querySnapshot.forEach((doc) => {
            let newObject = [doc.id: doc.data() ]
            response.push(newObject)
        })

        setPlants(response)
    }
    getPlants()
}, [])

Any help is greatly appreciated :)

CodePudding user response:

I think you are creating the new object (newObject) wrong. Try to create it like this:

   querySnapshot.forEach((doc) => {
       const newObject = {}
       newObject[doc.id] = doc.data()
       response.push(newObject)
   })

Or, you can do this:

   querySnapshot.forEach((doc) => {
       response.push({ [`${doc.id}`]: doc.data() })
   })
  • Related