我有json嵌套数组,如下所示:
Parent: {
Child1: [
{name:'grandchild1', value:'abc', checked:true},
{name:'grandchild2', value:'pqr', checked:false}
],
Child2: [
{name:'grandchild3', value:'abcd', checked:false},
{name:'grandchild4', value:'pqrs', checked:true}
],
parent2{...........}....
};
我需要将其转换为:
[
{
"filename":"Parent",
"children":[
{
"filename":"Child1",
"children":[
{
"filename":"grandchild1",
"type":"ts"
},
{
"filename":"grandchild2",
"type":"ts"
}
]
},
{
"filename":"Child2",
"children":[
{
"filename":"grandchild3",
"type":"ts"
},
{
"filename":"grandchild4",
"type":"ts"
}
]
}
]
},
{ filename:"Parent1"..........
},....
]
它是角形材料树的一部分。他们有示例代码Link
尝试以下代码:
Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
const value = obj[key];
const node = new FileNode();
node.filename = key;
if (value != null) {
if (typeof value === 'object') {
node.children = this.buildFileTree(value, level + 1);
} else {
node.type = value;
}
}
return accumulator.concat(node);
}, []);
}
但是没有得到我所需要的。
请建议我如何转换为以下格式,以便它接受相应的方式?
答案 0 :(得分:1)
const list = {Parent1 :{
Child1: [
{name:'grandchild1', value:'abc', checked:true},
{name:'grandchild2', value:'pqr', checked:false}
] ,
Child2: [
{name:'grandchild3', value:'abcd', checked:false},
{name:'grandchild4', value:'pqrs', checked:true}
]
}, Parent2 :{
Child1: [
{name:'grandchild1', value:'abc', checked:true},
{name:'grandchild2', value:'pqr', checked:false}
] ,
Child2: [
{name:'grandchild3', value:'abcd', checked:false},
{name:'grandchild4', value:'pqrs', checked:true}
]
}};
const res = []
for(let parent in list){
let parentTemp = {
filename : parent,
children : []
}
for(let child in list[parent]){
let childTemp = {filename : child, children : []};
for(let grandChild of list[parent][child]){
childTemp.children.push({filename : grandChild.name, type : grandChild.value, status: grandChild.checked});
}
parentTemp.children.push(childTemp);
}
res.push(parentTemp);
}
console.log(res);