我有对象集合的递归数组,需要将其转换为对象,
我尝试了以下类似方法,但我希望动态进行。
任何人都可以提出建议或分享您的想法对我有帮助
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",
}
}
答案 0 :(得分:1)
您可以使用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 }), {})