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根據(jù)某一層級的id輸出從上到下整個層級的id
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
相關(guān)閱讀更多精彩內(nèi)容
- 明朝衛(wèi)所制度從上到下的層級劃分分別是:中央的五軍都督府—— 各省的都指揮使司(正二品)——下轄若干個衛(wèi)(衛(wèi)指揮使是...
- 從上往下打印二叉樹 題目描述: 從上往下打印出二叉樹的每個節(jié)點,同層節(jié)點從左至右打印。 解題思路: 經(jīng)典題目,樹的...
- TODO: 理解數(shù)組中數(shù)字出現(xiàn)的次數(shù)的有限狀態(tài)機方法。 一、 劍指 Offer 32 - III. 從上到下打印二...