【问题标题】:JavaScript (ReactJS) comparing two ObjectsJavaScript (ReactJS) 比较两个对象
【发布时间】:2020-12-26 19:40:05
【问题描述】:

我有一个用户对象:

const data = [
{
  name: "John",
  lastName: "Doe",
  email: "stefa@gmail.com",
  password: "123",
  following: [{ id: "113"}, { id: "111" } }],
  id: "112",
},
{
  name: "Jane",
  lastName: "Doe",
  email: "dusica@gmail.com",
  password: "123",
  following: [{ id: "112" }],
  id: "113",
},
{
  name: "Mark",
  lastName: "Twain",
  email: "marko@gmail.com",
  password: "123",
  following: [],
  id: "111",
},
];

正如您所见,所有用户都有一个名为“following”的数组,该数组包含用户关注的用户的 id。我想访问该数组“关注”以找出未关注哪些用户。假设我们要检查 id="112" 的第一个用户 John Doe 的“关注”数组。

 const followers = [];
 let suggestions = null;

 props.users.forEach((user) => {
   if (user.id === '112') {
     user.following.forEach((item) => {
     followers.push(item);
    });
  }
 });

 followers.map((item) => {
   suggestions = props.users.map((user) => {
     if (user.id !== item.id && user.id !== '112) {
       console.log(item.id); 
       return <div>something</div>;
     }
   });
 });

我尝试过这样的事情,但结果不是我所期望的。正如我所说,我想返回未关注的用户并呈现它们,因为我希望它们可见,以便用户可以关注它们。我希望我是可以理解的。谢谢。

【问题讨论】:

  • 您可以将用户的 id 放在 Map 中,然后至少有一个其他用户,然后遍历 data 数组并查看当前用户的 id是否在Map 中。它比获取一个用户id然后在data数组中的其他用户对象的following数组中搜索它更有效

标签: javascript arrays reactjs object foreach


【解决方案1】:

这是一个负面的比较。 因此,您要过滤掉用户关注的所有用户。 您可以遍历每个用户并将其与以下数组进行比较。如果以下数组包含用户,则不要显示它。

 const notFollowing = allUsers.filter(user => 
     !currentUser.following.some(({ id }) => id === user.id)
 );

【讨论】:

  • 谢谢。我完全忘记了 filter() 方法。再次感谢!
猜你喜欢
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多