需求:递归从下面的数据中找到某一个值。例如:传入a1 ,找到a1所有在位置,并添加一个属性 expand: true,因为后台返回的数据层级不确定,得要递归才可以。export const json = [{ "name": "测试1", "children": [] }, { "name": "测试2", "children": [{ "name": "A区", "children": [{ "name": "a1", "children": null }, { "name": "a2", "children": null }, ] }, { "name": "B区", "children": [{ "name": "b1", "children": null }, { "name": "b2", "children": null }, ] } ] },]
2 回答
守候你守候我
TA贡献1802条经验 获得超10个赞
function addExpand(arr, find){
for(let k in arr){
let item = arr[k]
if(typeof item === 'object'){
addExpand(item, find);
} else{
if (item == find) {
arr.expand = true
}
}
}
return arr
}
let nJson = addExpand(json, 'a1')
添加回答
举报
0/150
提交
取消