let test = [{id:1},{id:5,children:[{id:6,children:[{id:7}]}]}]
function chbehavior(arr, id) {
let res;
(function deepId(arr, id) {
for (let a of arr) {
if (a.id === id) {
res = a;
} else if (a.children && !res) {
deepId(a.children, id);
}
}
})(arr, id);
return res;
}
let arrays = this.chbehavior(test, 7)
console.log(arrays) //{id:7}
function findId(data, id) {
for (let i = 0; i < data.length; i++) {
if (data[i].id === id) {
return data[i];
} else if (data[i].children) {
let found = findId(data[i].children, id);
if (found) return found;
}
}
}
console.log(findId(test, 7)) //{id:7}
多维数组递归查找
于 2020-08-19 18:16:44 首次发布