运用场景:
一个树形数据结构,后台返回最后一层的子集的id , 因为是联级选择器,我需要拿到所有的由所有父级id 组成的数组。
嵌套的级数是不确定的。
const data = [
{
id: 1,
name: '大别墅',
children: [
{
id: 11,
name: '卧室'
},
{
id: 12,
name: '卧室2'
},
{
id: 13,
name: '卧室3'
},
{
id: 14,
name: '厨房',
children: [
{
id: 141,
name: '厨房2',
children:[
{
id: 1413,
name: '冰箱'
}
]
},
{
id: 148,
name: '厨房3',
}
]
},
]
},
{
id: 2,
name: '小公寓',
children: [
{
id: 21,
name: '房间1'
},
{
id: 22,
name: '房间2'
},
{
id: 23,
name: '房间23'
},
{
id: 24,
name: '房间24'
},
]
}
];
console.log(find(data, 24))
function find (array, id) {
let stack = [];
let going = true;
let walker = (array, id) => {
array.forEach(item => {
if (!going) return;
stack.push(item['id']);
if (item['id'] === id) {
going = false;
} else if (item['children']) {
walker(item['children'], id);
} else {
stack.pop();
}
});
if (going) stack.pop();
}
walker(array, id);
return stack.join(',');
}