要将对象的平面数组转换为嵌套对象的数组,首先需要理解平面数组和嵌套对象数组的基本概念。
假设我们有一个平面数组,每个对象包含id
、name
和parentId
字段,我们希望将其转换为嵌套的对象数组。
const flatArray = [
{ id: 1, name: 'Root', parentId: null },
{ id: 2, name: 'Child1', parentId: 1 },
{ id: 3, name: 'Child2', parentId: 1 },
{ id: 4, name: 'GrandChild', parentId: 2 }
];
function buildNestedStructure(flatArray) {
const map = {};
const roots = [];
flatArray.forEach(item => {
map[item.id] = { ...item, children: [] };
});
flatArray.forEach(item => {
if (item.parentId !== null) {
map[item.parentId].children.push(map[item.id]);
} else {
roots.push(map[item.id]);
}
});
return roots;
}
const nestedArray = buildNestedStructure(flatArray);
console.log(JSON.stringify(nestedArray, null, 2));
[
{
"id": 1,
"name": "Root",
"parentId": null,
"children": [
{
"id": 2,
"name": "Child1",
"parentId": 1,
"children": [
{
"id": 4,
"name": "GrandChild",
"parentId": 2,
"children": []
}
]
},
{
"id": 3,
"name": "Child2",
"parentId": 1,
"children": []
}
]
}
]
通过上述方法,可以有效地将平面数组转换为嵌套对象数组,适用于多种需要层级数据表示的场景。
领取专属 10元无门槛券
手把手带您无忧上云