js 递归使用 遍历查找出 树形对象数组 的某特定id
需求:找出树形数组里面 canAccess 为true的id
var arr = [
{ id: 1, canAccess: false },
{ id: 2, canAccess: true },
{ id: 3, canAccess: false, children: [{ id: 4, canAccess: true }] },
{ id: 5, canAccess: false, children: [{ id: 6, canAccess: false, children: [{ id: 7, canAccess: true }] }] },
{
id: 8, canAccess: true, children: [{
id: 9, canAccess: true,
children: [{ id: 10, canAccess: false, children: [{ id: 11, canAccess: true }] }]
}]
}
]
let newArr = []; // 用来接收新id
var findCan = function (V) {
V.forEach(item => { // 把传入的数组循环遍历
if (item.canAccess === true) {
newArr.push(item.id); // item.canAccess 为true 把id添加到新数组
}
if (item.children) {
// console.log('有 children', item.children); // 有 children 的话就调用自身
findCan(item.children) // 递归调用自身
}
})
}
findCan(arr) // 调用函数
console.log(newArr);
需求:找出树形数组 把 canAccess 为true的一项 添加到新数组
var arr = [
{ id: 1, canAccess: false },
{ id: 2, canAccess: true },
{ id: 3, canAccess: false, children: [{ id: 4, canAccess: true }] },
{ id: 5, canAccess: false, children: [{ id: 6, canAccess: false, children: [{ id: 7, canAccess: true }] }] },
{
id: 8, canAccess: true, children: [{
id: 9, canAccess: true,
children: [{ id: 10, canAccess: false, children: [{ id: 11, canAccess: true }] }]
}]
}
]
let newArr = []; // 用来接收新id
var findCan = function (V) {
V.forEach(item => { // 把传入的数组循环遍历
if (item.canAccess === true) {
newArr.push(item); // item 为true 把该对象添加到新数组
}
if (item.children) {
// console.log('有 children', item.children); // 有 children 的话就调用自身
findCan(item.children) // 递归调用自身
}
})
}
findCan(arr) // 调用函数
console.log(newArr);
需求:根据传入的树形数组和 id 找出 该id 的一组信息 例如:根据该员工id找到该员工的一组成员
// 例如:根据该员工id找到该员工的一组成员
var array = [
{
id: 1,
children: [{
id: 2,
children: []
}]
},
{
id: 3,
children: []
},
{
id: 4,
children: [{
id: 5,
children: [{
id: 6,
children: []
},
{
id: 7,
children: []
}]
}]
}
]
let newArr;
let findAll = function (v, num) {
v.forEach(e => {
if (e.id === num) { newArr = e } // 某一项的id 等于 传入的id 就把该数组找出来
if (e.children.length > 0) {
findAll(e.children, num)
}
})
};
findAll(array, 4);
console.log(newArr);