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. 從上到下打印二...