JavaScript根据子级id递归查找至顶级id的集合
Posted web半晨
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript根据子级id递归查找至顶级id的集合相关的知识,希望对你有一定的参考价值。
1、代码
let recursionData = [
id: 1,
name: "一级",
children: [
id: 2,
name: "二级-1",
children: [
id: 7,
name: "三级-1",
children: [
id: 10,
name: "四级-1",
,
],
,
id: 8,
name: "三级-2",
,
],
,
id: 3,
name: "二级-2",
children: [
id: 5,
name: "三级-3",
,
id: 6,
name: "三级-4",
,
],
,
id: 4,
name: "二级-3",
children: [
id: 9,
name: "三级-5",
children: [
id: 11,
name: "四级-2",
,
],
,
],
,
],
,
];
function funRecursion(list, id)
for (let i in list)
if (list[i].id == id)
// return [list[i]];
return [list[i].id];
if (list[i].children)
let node = funRecursion(list[i].children, id);
if (node !== undefined)
// return node.concat(list[i]);
return node.concat(list[i].id);
;
console.log(funRecursion(recursionData, 10)); // [10, 7, 2, 1]
console.log(funRecursion(recursionData, 10).reverse()); // [1, 2, 7, 10]
2、相关链接
以上是关于JavaScript根据子级id递归查找至顶级id的集合的主要内容,如果未能解决你的问题,请参考以下文章