gpt4 book ai didi

javascript - 如何递归地将嵌套对象数组转换为平面对象数组?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:29 25 4
gpt4 key购买 nike

我有以下深度嵌套对象数组:

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 字段而不显着增加函数的复杂性?

最佳答案

每次迭代检查当前项目是否为“父”项目,如果是则重新分配label

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"}]}]}];

function getChildren(array, result = [], label = "") {
array.forEach(({ children, name, count }) => {
if (!label || name[1]) {
label = `${name} = `;
}
if (count) {
result.push({ count, name, label: label + name });
}
if (children) {
getChildren(children, result, label);
}
});
return result;
}

const res = getChildren(data);

console.log(res);

关于javascript - 如何递归地将嵌套对象数组转换为平面对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com