我有一个对象数组,包含来自对象数组的子项,我需要在父级数组中查找值,或者在此数组的子项中查找值等。可能需要使用递归算法实现。我尝试了以下代码:
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)
它返回源数组,但我需要包含文本“my”的数组