I am faced with a nested JSON array structure like this:
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{...........}....
};
I am looking to transform it into the following format:
[
{
"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"..........
},....
]
This structure is needed for an Angular Material tree. You can refer to the sample code provided in this Link
I have attempted to achieve this using the code snippet below:
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);
}, []);
}
However, the output did not match my requirements.
I would appreciate any suggestions on how to properly convert the structure to the specified format for it to function as intended.