1 回答

TA貢獻1834條經驗 獲得超8個贊
Array#filter我們可以首先使用 過濾掉沒有父級的項目,因為這些是我們需要保留在最終數組中的項目。
然后使用它們將它們映射到其子項并在每個項目中Array#find添加一個屬性:children
const mapToChild = (data) => {
return data
.filter(i => !i.parent)
.map(d => {
let children;
if(!d.parent){
children = data.filter(i => i.parent === d.id);
}
return children && children.length ? {...d, children} : d;
});
}
const data = [
{
id: 1,
text : "Hello world",
parent : null
},
{
id: 2,
text : "Hello world",
parent : null
},
{
id: 3,
text : "Hello world",
parent : 2
},
{
id: 4,
text : "Hello world",
parent : 1
},
{
id: 5,
text : "Hello world",
parent : 1
},
{
id: 6,
text : "Hello world",
parent : null
},
{
id: 7,
text : "Hello world",
parent : null
}
];
console.log(mapToChild(data));
編輯以處理嵌套子項:
Array#reduce當我們必須照顧嵌套的孩子時,我們可以使用:
const mapToChild = (data) => {
return data.reduce((r, o) => {
const children = data.filter(i => i.parent == o.id);
if(children && children.length) {
o.children = children;
}
!o.parent && r.push(o);
return r;
}, []);
}
const data = [
{
id: 2,
text : "Hello world",
parent : null
},
{
id: 3,
text : "Hello world",
parent : 2
},
{
id: 4,
text : "Hello world",
parent : 3
}
];
console.log(mapToChild(data));
添加回答
舉報