gpt4 book ai didi

javascript - lodash递归查找数组中的项目

转载 作者:行者123 更新时间:2023-12-04 17:07:48 26 4
gpt4 key购买 nike

lodash中最简单的解决方案是通过例如值为'Item-1-5-2'的'text'字段递归查找数组中的项目?

const data = [
{
id: 1,
text: 'Item-1',
children: [
{ id: 11, text: 'Item-1-1' },
{ id: 12, text: 'Item-1-2' },
{ id: 13, text: 'Item-1-3' },
{ id: 14, text: 'Item-1-4' },
{
id: 15,
text: 'Item-1-5',
children: [
{ id: 151, text: 'Item-1-5-1' },
{ id: 152, text: 'Item-1-5-2' },
{ id: 153, text: 'Item-1-5-3' },
]
},
]
},
{
id: 2,
text: 'Item-2',
children: [
{ id: 21, text: 'Item-2-1' },
{ id: 22, text: 'Item-2-2' },
{ id: 23, text: 'Item-2-3' },
{ id: 24, text: 'Item-2-4' },
{ id: 25, text: 'Item-2-5' },
]
},
{ id: 3, text: 'Item-3' },
{ id: 4, text: 'Item-4' },
{ id: 5, text: 'Item-5' },
];

谢谢你!

最佳答案

在纯 Javascript 中,您可以使用 Array#some 递归地。

function getObject(array, key, value) {
var o;
array.some(function iter(a) {
if (a[key] === value) {
o = a;
return true;
}
return Array.isArray(a.children) && a.children.some(iter);
});
return o;
}

var data = [{ id: 1, text: 'Item-1', children: [{ id: 11, text: 'Item-1-1' }, { id: 12, text: 'Item-1-2' }, { id: 13, text: 'Item-1-3' }, { id: 14, text: 'Item-1-4' }, { id: 15, text: 'Item-1-5', children: [{ id: 151, text: 'Item-1-5-1' }, { id: 152, text: 'Item-1-5-2' }, { id: 153, text: 'Item-1-5-3' }, ] }, ] }, { id: 2, text: 'Item-2', children: [{ id: 21, text: 'Item-2-1' }, { id: 22, text: 'Item-2-2' }, { id: 23, text: 'Item-2-3' }, { id: 24, text: 'Item-2-4' }, { id: 25, text: 'Item-2-5' }, ] }, { id: 3, text: 'Item-3' }, { id: 4, text: 'Item-4' }, { id: 5, text: 'Item-5' }, ];

console.log(getObject(data, 'text', 'Item-1-5-2'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - lodash递归查找数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39896537/

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