请帮助我获得更好的优化功能,该功能可以将数组转换为结构化数组,如下所示。
raw data
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
}
]
formatted data
let structredData = [
{
id: 1,
text : "Hello world",
parent : null,
children : [
{
id: 4,
text : "Hello world",
parent : 1
},
{
id: 5,
text : "Hello world",
parent : 1
}
]
},
{
id: 2,
text : "Hello world",
parent : null,
children : [
{
id: 3,
text : "Hello world",
parent : 2
}
]
},
{
id: 6,
text : "Hello world",
parent : null
},
{
id: 7,
text : "Hello world",
parent : null
}
]
我只是想在我的Web应用程序中实现嵌套注释功能,所以我认为如果以这种格式来结构化数据会容易得多。还请让我知道什么是最好的选择。
答案 0 :(得分:1)
我们首先可以使用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));