1.算法代码
function findById(id,list) {
let queue = [].concat(list);
while (queue.length > 0) {
const item = queue.shift();
if (String(item.id) === String(id)) return item;
if (item.children) queue = queue.concat(item.children);
}
return null;
}
2.调用
const list = [
{
id: 1,
name: '数学',
children: [
{
id: 2,
name: '微积分',
},
]
},
{
id: 8,
name: '政治',
children: [
{
id: 9,
name: '毛概',
children: [
{
id: 10,
name: '毛泽东思想'
}
]
},
]
},
];
console.log(findById(10,list));