【发布时间】: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