简体   繁体   English

如何从 Firestore 中的嵌套 map 中提取数据?

[英]How to extract data from a nested map in firestore?

I have a collection users and it has multiple documents.我有一个集合users ,它有多个文档。 Inside each document, there is a field called contacts .在每个文档中,都有一个名为contacts的字段。 It is of map type.它是 map 型。 Inside contacts, I have another map-type data.在联系人内部,我有另一个地图类型的数据。

My database:我的数据库: 在此处输入图像描述

I am trying to store my contacts data in contactDetailsArr array like:我正在尝试将我的联系人数据存储在contactDetailsArr数组中,例如:

[{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.请指导我做错了什么。

If you log the values in your for loop, it is easy to see the problem:如果您在 for 循环中记录值,则很容易发现问题:

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

This logs:这记录:

0 0

1 1

So you need to still look up the object at the index:所以你仍然需要在索引处查找 object:

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

Or with a forEach list comprehension:或者使用forEach列表理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM