我有一个对象数组,其中包含对象数组中的子项,我需要在父数组中查找值或在该数组的子项中查找值等。可能是递归的。我试过这样:
var array = [
{
id: 1,
value: 'value',
children: null
},
{
id: 2,
value: 'my value',
children: [
{
id: 'child1',
value: 'my value',
children: null
},
{
id: 'child2',
value: 'value',
children: null
},
{
id: 'child3',
value: 'value,
children: [
{
id: 'childchild1',
value: 'my value',
children: null
}
]
}
]
},
{
id: 3,
value: 'value',
children: null
},
{
id: 4,
value: 'my value',
children: null
}
]
function find(searchData, target){
return target.filter((f)=>{
if(f.value.includes(searchData)){
return true
}
if(f.children){
return find(searchData, f.children)
}
})
}
find('my', array)
它返回源数组,但我需要包含文本“我的”的数组
最佳答案
因为你有一个嵌套结构,你不能使用 .filter
来获取所有嵌套对象 - .filter
只会返回给你最顶层的匹配对象等级。相反,在初始调用时定义一个空数组,然后在项目通过测试时 push
到该数组,并将该数组传递给每个递归调用。最后,返回该数组:
var array=[{id:1,value:'value',children:null},{id:2,value:'my value',children:[{id:'child1',value:'my value',children:null},{id:'child2',value:'value',children:null},{id:'child3',value:'value',children:[{id:'childchild1',value:'my value',children:null}]}]},{id:3,value:'value',children:null},{id:4,value:'my value'}];
function find(searchData, target, accum=[]){
target.forEach((f)=>{
if(f.children){
find(searchData, f.children, accum)
}
if(f.value.includes(searchData)){
accum.push(f);
}
});
return accum;
}
console.log(find('my', array));
(通过浏览器控制台可能比通过堆栈代码段控制台更容易看到结果)
关于javascript - 在对象数组中查找包含对象数组中的子对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865538/