gpt4 book ai didi

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

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

我有需要转换为对象的对象集合的递归数组,

我尝试了类似下面的方法,但我想要动态的。

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

let arr = list;
const jsonObj = {};
const arrayToObject = (array, keyField) =>
array.reduce((obj, item) => {
obj[item[keyField]] = item
return obj
}, {})
arr.forEach((item) => {
jsonObj[item.key] = {};
if(item.children.length > 0) {
jsonObj[item.key] = arrayToObject(item.children, 'key');
}
})

输入

list =  [
{
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: [] }
]
},
];

输出

{
"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",
}
}

最佳答案

您可以使用reduce 递归循环数组。如果当前对象有一个非零的 children 数组,则递归调用 transform。否则,使用 value 作为累加器中的 key

const list = [{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:[]}]}];

function transform(array) {
return array.reduce((r, { key, value, children }) => {
if (children.length)
r[key] = transform(children)
else
r[key] = value;
return r;
}, {})
}

console.log(transform(list))

使用箭头函数和 Object.assgin() 的一行代码:

const transform = (array) => array.reduce((r, { key, value, children }) => 
Object.assign(r, { [key]: children.length ? transform(children): value }), {})

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

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