gpt4 book ai didi

javascript - 在另一个数组中的数组中查找对象

转载 作者:行者123 更新时间:2023-12-03 16:55:50 24 4
gpt4 key购买 nike

let bigArray = [
{
Name: 'Trump',
children: [
{Name: 'TrumpChild1', City: 'city1'},
{Name: 'TrumpChild2', City: 'city2'}
]
},
{
Name: 'Barack Obama',
children: [
{Name: 'Barack Obama Child1', City: 'city3'},
{Name: 'Barack Obama Child2', City: 'city4'}
]
},
{
Name: 'Clinton',
children: [
{Name: 'Clinton Child 1', City: 'city5'},
{Name: 'Clinton Child2', City: 'city6'}
]
},

]

我想从另一个数组中的数组中找到一个对象
bigArray.find(b => b.children.find(c=>c.City === 'city1'))

上面的代码返回 ARRAY 父亲
bigArray.forEach(b => b.children.find(c=>c.City === 'city1'))

这返回未定义

返回所需对象的最佳方法是什么?

最佳答案

您可以先将此数组展平为内部对象数组,然后使用 filter() find() .

let bigArray = [
{
Name: 'Trump',
children: [
{Name: 'TrumpChild1', City: 'city1'},
{Name: 'TrumpChild2', City: 'city2'}
]
},
{
Name: 'Barack Obama',
children: [
{Name: 'Barack Obama Child1', City: 'city3'},
{Name: 'Barack Obama Child2', City: 'city4'}
]
},
{
Name: 'Clinton',
children: [
{Name: 'Clinton Child 1', City: 'city5'},
{Name: 'Clinton Child2', City: 'city6'}
]
}
];

let all = bigArray.reduce((prev, next) => prev.concat(next.children), []);
let result = all.find(obj => obj.City === 'city1');
console.log(result);

// if there can be multiple matches then use filter
let results = all.filter(obj => obj.City === 'city1');
console.log(results);

关于javascript - 在另一个数组中的数组中查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50381450/

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