gpt4 book ai didi

javascript - 在javascript es6中将嵌套对象转换为递归数组或嵌套数组

转载 作者:行者123 更新时间:2023-11-30 19:32:12 25 4
gpt4 key购买 nike

我工作了嵌套对象,我想将其转换为递归数组或嵌套数组。

我尝试像下面这样迭代对象,但它正在创建单个数组对象。

任何人都可以提出建议或分享您的想法,这对我有帮助

        iterate(obj) {
for (let property in obj) {
this.configArray.push({key: property,children: [], isValue: false, value: ''});
if (obj.hasOwnProperty(property)) {
const index = Object.keys(obj).indexOf(property);
if (typeof obj[property] == "object") {
this.iterate(obj[property]);
}
else {
this.configArray[index].children.push({ key: property, value: obj[property], isValue: true, children: [] });
}
}
}
}

输入

{
"Parent 1": {
"11": "Child 1",
"12": "Child 2",
},
"Parent 2": {
"20": {
"21": "Grand Child 1",
"22": "Grand Child 2",
}
},
"Parent 3": {
"31": "Child 1",
"32": "Child 2",
}

输出

  [
{
key: "Parent 1",
value: "",
children: [
{ key: 11, value: "Child 1", children: [] },
{ key: 12, value: "Child 2", children: [] }
]
},
{
key: "Parent 2",
value: "",
children: [
{
key: 20,
value: "",
children: [
{ key: 21, value: "Grand Child 1", children: [] },
{ key: 22, value: "Grand Child 2", children: [] }
]
}
]
},
{
key: "Parent 3",
value: "",
children: [
{ key: 31, value: "Child 1", children: [] },
{ key: 32, value: "Child 2", children: [] }
]
},
];

最佳答案

如果 value 是一个对象,您可以采用递归方法映射值或子项。

function transform(object) {
return Object
.entries(object)
.map(([key, value]) => Object.assign({ key }, value && typeof value === 'object'
? { value: '', children: transform(value) }
: { value, children: [] }
));
}

var data = { "Parent 1": { 11: "Child 1", 12: "Child 2" }, "Parent 2": { 20: { 21: "Grand Child 1", 22: "Grand Child 2" } }, "Parent 3": { 31: "Child 1", 32: "Child 2" } },
result = transform(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在javascript es6中将嵌套对象转换为递归数组或嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56314019/

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