简体   繁体   English

在 Javascript react-native 中过滤 object

[英]Filtering object in Javascript react-native

I have this structure of data: This is source code of my chats component: https://pastebin.com/JJQFQyHi我有这样的数据结构:这是我的聊天组件的源代码: https://pastebin.com/JJQFQyHi 在此处输入图像描述

every chat has two members, I want to display other persons data profile_picture and username in my chat list.每个聊天都有两个成员,我想在我的聊天列表中显示其他人的数据 profile_picture 和用户名。 So i want to delete unnecessary data.所以我想删除不必要的数据。 I use firebase realtime database.我使用 firebase 实时数据库。 This is how i tried to rid off unnecessary data.这就是我试图摆脱不必要的数据的方式。

getChats = _userId => {
    let data;
    var readedData = firebase
      .database()
      .ref('chats')
      .orderByChild('members/' + _userId)
      .equalTo(true);
    readedData.once('value', snapshot => {
      this.setState({ chats: snapshot.val() });
      // console.log(JSON.stringify(this.state.chats));
      data = snapshot.val();
      delete data._userId;
      delete data.members;
      console.log(data);
    });
  };

console log:控制台日志:

> {"-M4NzlagjmeFH7IR_Api": {"lwcIQTcpAae4e38hrD2K5Ar76W93": {"data":
> [Object]}, "members": {"lwcIQTcpAae4e38hrD2K5Ar76W93": true,
> "tempuser": true}, "tempuser": {"data": [Object]}},
> "-M4O-aIxt9w2iKuCDweN": {"lwcIQTcpAae4e38hrD2K5Ar76W93": {"data":
> [Object]}, "members": {"lwcIQTcpAae4e38hrD2K5Ar76W93": true,
> "tempuser": true}, "tempuser": {"data": [Object]}},
> "-M4Q05H1lEUIyWqLJyoQ": {"lwcIQTcpAae4e38hrD2K5Ar76W93": {"data":
> [Object]}, "members": {"lwcIQTcpAae4e38hrD2K5Ar76W93": true}},
> "-M649remSnfBLBuYJIXO": {"lwcIQTcpAae4e38hrD2K5Ar76W93": {"data":
> [Object]}, "members": {"lwcIQTcpAae4e38hrD2K5Ar76W93": true,
> "tempuser": true}, "messages": {"-M64A0ydh-WJstJIFIr1": [Object],
> "-M66cLC6OjQhlyNN5uDq": [Object], "-M66eWivUodiVtHIkfGv": [Object]},
> "tempuser": {"data": [Object]}}}

When you refer call snapshot.val() you get an object as you have shown in the console log.当您调用snapshot.val()时,您会得到一个 object,如控制台日志中所示。 This value is then assigned to data .然后将此值分配给data

When you try to delete keys from this data object, Javascript tries to remove them from the top level of the object.当您尝试从该data object 中delete密钥时,Javascript 会尝试从 object 的顶层删除它们。 Since there are no properties with the given names ( members or _userId ) at the top level, it fails to filter anything out.由于顶层没有具有给定名称( members_userId )的属性,因此无法过滤掉任何内容。

If you need a list of tempuser s, you can build it using the forEach method of the snapshot .如果你需要一个tempuser的列表,你可以使用snapshotforEach方法来构建它。

readedData.once("value", (snapshot) => {
  const userData = [];
  snapshot.forEach((data) => {
    userData.push(data.tempuser)
  });

  console.log(userData); // this should contain the tempusers.
});

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

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