假設我有一個如下的物件陣列串列
[
{id:1,parent:0,name:"test 1",subs:[3,4]},
{id:2,parent:0,name:"test 2",subs:[5,6]},
{id:3,parent:1,name:"test 3",subs:[7]},
{id:4,parent:1,name:"test 4",subs:[]},
{id:5,parent:2,name:"test 5",subs:[]},
{id:6,parent:2,name:"test 6",subs:[8]},
{id:7,parent:3,name:"test 7",subs:[]},
{id:8,parent:6,name:"test 8",subs:[]},
]
現在我想用可能的子名稱制作名稱字串陣列
如果考慮上面的陣列,那么輸出應該如下所示
[
"test 1",
"test 1 - test 3",
"test 1 - test 4",
"test 1 - test 3 - test 7",
"test 2",
"test 2 - test 5",
"test 2 - test 6",
"test 2 - test 6 - test 8"
]
請幫我解決。先感謝您
uj5u.com熱心網友回復:
此解決方案構建一棵樹并迭代孩子。
const
data = [{ id: 1, parent: 0, name: "test 1", subs: [3, 4] }, { id: 2, parent: 0, name: "test 2", subs: [5, 6] }, { id: 3, parent: 1, name: "test 3", subs: [7] }, { id: 4, parent: 1, name: "test 4", subs: [] }, { id: 5, parent: 2, name: "test 5", subs: [] }, { id: 6, parent: 2, name: "test 6", subs: [8] }, { id: 7, parent: 3, name: "test 7", subs: [] }, { id: 8, parent: 6, name: "test 8", subs: [] }],
getTree = (data, root) => {
const t = {};
data.forEach(o => ((t[o.parent] ??= {}).children ??= []).push(Object.assign(t[o.id] ??= {}, o)));
return t[root].children;
},
flat = p => o => (name => [
name,
...(o.children || []).flatMap(flat(name))
])(p (p && ' - ') o.name),
tree = getTree(data, 0),
result = tree.flatMap(flat(''));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
使用的方法subs和參考的物件id。
const
data = [{ id: 1, parent: 0, name: "test 1", subs: [3, 4] }, { id: 2, parent: 0, name: "test 2", subs: [5, 6] }, { id: 3, parent: 1, name: "test 3", subs: [7] }, { id: 4, parent: 1, name: "test 4", subs: [] }, { id: 5, parent: 2, name: "test 5", subs: [] }, { id: 6, parent: 2, name: "test 6", subs: [8] }, { id: 7, parent: 3, name: "test 7", subs: [] }, { id: 8, parent: 6, name: "test 8", subs: [] }],
root = [],
ids = Object.fromEntries(data.map(o => [o.id, (o.parent|| root.push(o.id), o)])),
flat = p => id => (name => [
name,
...ids[id].subs.flatMap(flat(name))
])(p (p && ' - ') ids[id].name),
result = root.flatMap(flat(''));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/413808.html
標籤:
上一篇:Vector{Union{T,Missing}}是Vector{T}大小的兩倍嗎?
下一篇:如何獲取每個屬性的總和值
