gpt4 book ai didi

javascript - 如何在嵌套数组上使用 find() 方法?

转载 作者:行者123 更新时间:2023-11-30 11:07:00 30 4
gpt4 key购买 nike

在此示例中,您可以看到 find 方法在此数组中工作正常:

var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];


console.log(inventory.find(fruit => fruit.name === 'cherries'));
// { name: 'cherries', quantity: 5 }

一旦我再添加一个级别并尝试在其中查找项目,它就是找不到它,它显示未定义:

var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5, type: [
{name: 'rainier', quantity: 3},
{name: 'bing', quantity: 2}
]}
];


console.log(inventory.find(fruit => fruit.name === 'bing'));
// undefined
// should be: { name: 'bing', quantity: 2 }

所以我想还有其他方法可以做到这一点,但我不知道也找不到任何东西。

最佳答案

您的代码不允许使用可选的 type 数组。假设您想进行深度优先搜索,您可以将回调设为命名函数并递归使用它,请参阅评论:

var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5, type: [
{name: 'rainier', quantity: 3},
{name: 'bing', quantity: 2}
]}
];

// Define the function
function find(array, name) {
// Loop the entries at this level
for (const entry of array) {
// If we found it, return it
if (entry.name === name) {
return entry;
}
// If not but there's a type array, recursively search it
if (Array.isArray(entry.type)) {
const found = find(entry.type, name);
if (found) {
// Recursive search found it, return it
return found;
}
}
}
// If execution falls off the end, it's effectively `return undefined;`
}
console.log(find(inventory, 'bing'));

关于javascript - 如何在嵌套数组上使用 find() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55197979/

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