const array = [
{
id: 'A',
name: 'A',
children: [
{
id: 'A-1',
name: 'A-1',
children: [
{
id: 'A-1-1',
name: 'A-1-1',
},
{
id: 'A-1-2',
name: 'A-1-2',
},
{
id: 'A-1-3',
name: 'A-1-3',
},
]
},
{
id: 'A-2',
name: 'A-2',
children: [
{
id: 'A-2-1',
name: 'A-2-1',
},
{
id: 'A-2-2',
name: 'A-2-2',
},
{
id: 'A-2-3',
name: 'A-2-3',
},
]
},
{
id: 'A-3',
name: 'A-3',
children: [
{
id: 'A-3-1',
name: 'A-3-1',
},
{
id: 'A-3-2',
name: 'A-3-2',
},
{
id: 'A-3-3',
name: 'A-3-3',
},
]
},
]
},
{
id: 'B',
name: 'B',
children: [
{
id: 'B-1',
name: 'B-1',
children: [
{
id: 'B-1-1',
name: 'B-1-1',
},
{
id: 'B-1-2',
name: 'B-1-2',
},
{
id: 'B-1-3',
name: 'B-1-3',
},
]
},
{
id: 'B-2',
name: 'B-2',
children: [
{
id: 'B-2-1',
name: 'B-2-1',
},
{
id: 'B-2-2',
name: 'B-2-2',
},
{
id: 'B-2-3',
name: 'B-2-3',
},
]
},
{
id: 'B-3',
name: 'B-3',
children: [
{
id: 'B-3-1',
name: 'B-3-1',
},
{
id: 'B-3-2',
name: 'B-3-2',
},
{
id: 'B-3-3',
name: 'B-3-3',
},
]
},
]
},
{
id: 'C',
name: 'C',
children: [
{
id: 'C-1',
name: 'C-1',
children: [
{
id: 'C-1-1',
name: 'C-1-1',
},
{
id: 'C-1-2',
name: 'C-1-2',
},
{
id: 'C-1-3',
name: 'C-1-3',
},
]
},
{
id: 'C-2',
name: 'C-2',
children: [
{
id: 'C-2-1',
name: 'C-2-1',
},
{
id: 'C-2-2',
name: 'C-2-2',
},
{
id: 'C-2-3',
name: 'C-2-3',
},
]
},
{
id: 'C-3',
name: 'C-3',
children: [
{
id: 'C-3-1',
name: 'C-3-1',
},
{
id: 'C-3-2',
name: 'C-3-2',
},
{
id: 'C-3-3',
name: 'C-3-3',
},
]
},
]
}
]
function findPathByValue(tree, targetValue) {
for (const node of tree) {
if (node.id === targetValue) {
return [node.id];
}
if(node.children) {
const childPath = findPathByValue(node.children, targetValue);
if (childPath) {
return [node.id, ...childPath];
}
}
}
return undefined;
}
console.log(findPathByValue(array, 'A-3-3'))
// [ 'A', 'A-3', 'A-3-3' ]
js根据某一层级的id输出从上到下整个层级的id
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 明朝卫所制度从上到下的层级划分分别是:中央的五军都督府—— 各省的都指挥使司(正二品)——下辖若干个卫(卫指挥使是...
- TODO: 理解数组中数字出现的次数的有限状态机方法。 一、 剑指 Offer 32 - III. 从上到下打印二...