【问题标题】:Filter object to get unknown user data过滤对象以获取未知用户数据
【发布时间】:2020-05-07 16:23:08
【问题描述】:

大家好,我有以下数据: 当我 console.log(Object.entries(data)) 我得到这个: https://pastebin.com/jPyRuxFX

我一直都知道这个对象中有我的用户 ID:lwcIQTcpAae4e38hrD2K5Ar76W93 成员对象和消息对象。我想过滤它,以便只有其他用户数据。 另一个用户 ID 可以是任何唯一键它在对象中,但我在任何变量中都没有它。 所以我需要过滤掉所有数据。这是我尝试过的:

 getChats = _userId => {
let data;
let usersData = [];
var readedData = firebase
  .database()
  .ref('chats')
  .orderByChild('members/' + _userId)
  .equalTo(true);
readedData.once('value', snapshot => {
  data = snapshot.val();

  const temp = { ...data };
  const filtered = Object.entries(data).map(duom =>
    duom
      .filter(user => user !== firebase.auth().currentUser.uid)
      .filter(user => !user.members)
      .filter(user => !user.messages),
  );

  console.log('filtered data: ' + JSON.stringify(data[filtered[0][0]]));

  this.setState({ chats: data, usersData: usersData });
  return true;
});

};

但结果是这样的:[["-M6cy1JNy1V5cs35StW-"],["-M4O-aIxt9w2iKuCDweN"],["-M4NzlagjmeFH7IR_Api"]] 我做错了什么,如何编辑这个过滤器?

我想要的结果在每个对象中:

“临时用户”:{ "用户名":"Egle", "profile_picture":"https://scontent.fkun1-1.fna.fbcdn.net/v/t1.0-9/38612482_1935470283165234_1771800590876147712_n.jpg?_nc_cat=111&_nc_sid=85a577&_nc_ohc=3rVHabbNJ3kAX9_0FBq&_nc_ht=scontent.fkun1-1.fna&oh=4277fff9a1441726bbf0efe18b44fae0&oe=5E9AA1F7" }

【问题讨论】:

  • 您当前的数据结构可以很容易地找到聊天室的成员。然而,为用户找到聊天室并不容易。要允许后者,您需要添加一个额外的数据结构 member_chats/$uid: { chatid1: true, chatid2: true } 在此处查看我的更长解释:stackoverflow.com/questions/40656589/…
  • 要为用户查找聊天室,我使用这个:.orderByChild('members/' + _userId) .equalTo(true);到目前为止效果很好。你知道我该如何过滤数据吗?
  • 您当前的代码要么要求您为每个 UID 定义一个索引,要么它会从所有 chats 中提取所有数据以执行查询。我在“您只能索引已知属性”部分的链接中的答案中更详细地解释了这一点

标签: javascript firebase firebase-realtime-database


【解决方案1】:

所以我设法像这样过滤数据:

const filtered = Object.entries(data).map(([key, value]) =>
        Object.keys(value)
          .filter(value => value !== _userId)
          .filter(value => value !== 'members')
          .filter(value => value !== 'messages'),
      );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2016-12-27
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多