简体   繁体   中英

Filtering object in Javascript react-native

I have this structure of data: This is source code of my chats component: https://pastebin.com/JJQFQyHi 在此处输入图像描述

every chat has two members, I want to display other persons data profile_picture and username in my chat list. So i want to delete unnecessary data. I use firebase realtime database. 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. This value is then assigned to data .

When you try to delete keys from this data object, Javascript tries to remove them from the top level of the object. Since there are no properties with the given names ( members or _userId ) at the top level, it fails to filter anything out.

If you need a list of tempuser s, you can build it using the forEach method of the snapshot .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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