Reputation: 372
I'm trying to transform my data on client side from this format:
[{
"id": 1,
"name": "dad",
"parent": [],
"children": [{
"group": {
"id": 2,
"name": "child1",
"parent": [{
"parent": 1
}]
}
},
{
"group": {
"id": 3,
"name": "child2",
"parent": [{
"parent": 1
}]
}
},
{
"group": {
"id": 8,
"name": "child3",
"parent": [{
"parent": 1
}]
}
}
]
}]
to this format:
[{
id: 1,
name: "parent",
parent: null,
children: [{
id: 2,
name: "child1",
parent: {
id: 1
},
children: []
},
{
id: 3,
name: "child2",
parent: {
id: 1
},
children: []
}
]
}]
key points:
I can't find a transformation library in npm to use and i need the data to be in that exact format to use in 'react-vertical-tree' component (didn't find any other good looking vertical tree component in react).
Upvotes: 1
Views: 127
Reputation: 386540
You could map new objects with converted parts.
const convert = o => {
var children;
if ('group' in o) o = o.group;
if ('children' in o) children = o.children.map(convert);
return Object.assign({}, o, { parent: o.parent.length ? { id: o.parent[0].parent } : null }, children && { children });
};
var data = [{ id: 1, name: "dad", parent: [], children: [{ group: { id: 2, name: "child1", parent: [{ parent: 1 }] } }, { group: { id: 3, name: "child2", parent: [{ parent: 1 }] } }, { group: { id: 8, name: "child3", parent: [{ parent: 1 }] } }] }],
result = data.map(convert);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1