gpt4 book ai didi

javascript - 如何访问对象中子元素的值?

转载 作者:行者123 更新时间:2023-11-28 03:09:14 24 4
gpt4 key购买 nike

我想访问每个用户的 friend 数组(数组的值是用户的ID)并返回给定用户( friend )的 friend 数组的值

const users = [
{
"id": 1,
"firstName": "Paul",
"surname": "Crowe",
"friends": [2]
},
{
"id": 2,
"firstName": "Rob",
"surname": "Fitz",
"friends": [1,3]
},
{
"id": 3,
"firstName": "Ben",
"surname": "O'Carolan",
"friends": [2]
},

这是我尝试过的:

const fof = users.filter(user => {
if (friend == user.id) {
return true;
}
});

最佳答案

您可以使用filter方法来查找 friend ,然后map他的 friend :

const idPerson = 2;
const idFriends = users.filter(f => f.id == idPerson).flatMap(({friends})=> (friends));
const uniqueUsers = new Map(users.map(u => ([u.id, u])));
const friends = idFriends.map(id => ({...uniqueUsers.get(id)}));

一个例子:

const users = [
{
"id": 1,
"firstName": "Paul",
"surname": "Crowe",
"friends": [2]
},
{
"id": 2,
"firstName": "Rob",
"surname": "Fitz",
"friends": [1, 3]
},
{
"id": 3,
"firstName": "Ben",
"surname": "O'Carolan",
"friends": [2]
}
];

const idPerson = 2;
const idFriends = users.filter(f => f.id == idPerson).flatMap(({friends})=> (friends));
const uniqueUsers = new Map(users.map(u => ([u.id, u])));
const friends = idFriends.map(id => ({...uniqueUsers.get(id)}));
console.log(friends);

关于javascript - 如何访问对象中子元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60306312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com