获取某一颗树下面的某一个节点及其子节点
var cId = 4;
var tree = [
{
id: 0,
children: [
{
id: 1,
children: [
{
id: 3
}
]
},
{
id: 2,
children: [
{
id: 4,
children: [
{
id: 5,
children: [
{
id: 6
}
]
},
{
id: 20
},
{
id: 21
}
]
},
{
id: 7,
children: [
{
id: 8
}
]
}
]
},
{
id: 9,
children: [
{
id: 10,
children: [
{
id: 11
}
]
}
]
}
]
}
];
var res = []
// false 代表只找不查 true 代表找也查
function findChildren(item, flag) {
// 判断是否找到那个节点,如果找到则把flag改为true
if (item.id === cId) {
flag = true
}
// 如果flag为true,那么就存入子数组
if (flag) {
res.push(item.id)
}
if (!item.children) {
return;
}
item.children.forEach(function (child) {
findChildren(child, flag);
})
}
tree.forEach(function (item) {
findChildren(item, false)
});
console.log(res);