我有一个深度嵌套对象的数组:
我想要转换的方式是这样的:
我创建了一个递归函数,将嵌套的数组转换成扁平化对象数组。
以下是我的代码:
这是我得到的输出:
问题在于我需要将
const data = [
{
name: "foo",
children:[
{
count: 1,
name: "A"
},
{
count: 2,
name: "B"
}
]
},
{
name: "bar",
children: [
{
count: 3,
name: "C",
children: [
{
count: 4,
name: "D"
}
]
}
]
}
]
我想要转换的方式是这样的:
const expectedStructure = [
{
count: 1,
name: "A",
label: "foo = A"
},
{
count: 2,
name: "B",
label: "foo = B"
},
{
count: 3,
name: "C",
label: "bar = C"
},
{
count: 4,
name: "D",
label: "bar = D"
}
]
我创建了一个递归函数,将嵌套的数组转换成扁平化对象数组。
以下是我的代码:
function getChildren(array, result=[]) {
array.forEach(({children, ...rest}) => {
result.push(rest);
if(children) {
getChildren(children, result);
}
});
return result;
}
这是我得到的输出:
[ { name: 'foo' },
{ count: 1, name: 'A' },
{ count: 2, name: 'B' },
{ name: 'bar' },
{ count: 3, name: 'C' },
{ count: 4, name: 'D' } ]
问题在于我需要将
label
字段添加到输出数组中的每个对象,但我找不到解决方案,而不必通过多次迭代最终数组来进行所需的转换。如何在不大幅增加函数复杂性的情况下正确插入 label
字段?
name
属性会向下传递到其下面的所有层级以用于标签。 - Barmar