How to extract data from a nested map in firestore?

Viewed 20

I have a collection users and it has multiple documents. Inside each document, there is a field called contacts. It is of map type. Inside contacts, I have another map-type data.

My database: enter image description here

I am trying to store my contacts data in contactDetailsArr array like:

[{userId: GA3yfqLaaTaDugSrFOQujnj34Y13,
  lastMessage:"Here there!!!",
  time: t {seconds: 1663220632, nanoseconds: 36000000}
},
{userId: TZjQb8yoYfQbowloQk1uLRCCPck1,
 lastMessage:"How are you?",
 time:t {seconds: 1663306634, nanoseconds: 859000000}
}]

but I am getting my array as

[{userId: GA3yfqLaaTaDugSrFOQujnj34Y13,
  lastMessage:undefined,
  time:undefined
},
{userId: TZjQb8yoYfQbowloQk1uLRCCPck1,
 lastMessage:undefined,
 time:undefined
}]

Here is my code:

export const getUserContacts= () =>{
  const contactDetailsArr=[];

  db.collection("users").doc(userId).get()   //userId is equal to "3aTGU..."
  .then(docs=>{

    const contactsObject= docs.data().contacts;
    
    for(let contact in contactsObject){

      
      contactDetailsArr.push({userId: contact, 
        lastMessage: contact.lastMsg,
        time: contact.lastMsgTime
      })
    }


  })
  .catch(err=>{
    console.log(err);
  })
  
}

If maps are objects then why I am able to extract data as we do in the case of objects. Please guide what I am doing wrong.

1 Answers

If you log the values in your for loop, it is easy to see the problem:

for(let contact in contactsObject){
  console.log(contact);
}

This logs:

0

1

So you need to still look up the object at the index:

for(let i in contactsObject){
  console.log(contactsObject[i]);
}

Or with a forEach list comprehension:

contactsObject.forEach((contact) => {
  console.log(contact, contact.userId, contact.lastMessage, contact.time);
}
Related