Reputation: 11
I need to convert js object like this:
{
"id": 1,
"name": "A",
"parent": null,
"children": [
{
"id": 2,
"name": "B",
"parent": 1,
"children": []
},
{
"id": 3,
"name": "C",
"parent": 1,
"children": [
{
"id": 4,
"name": "D",
"parent": 3,
"children": []
}
]
}
]
}
to another like this:
{
"А": [
{
"B": "value",
"C": [
{
"D": "value"
}
]
}
]
}
I wrote the function, but it returns the wrong object with several nested arrays:
const convert = (obj) => {
return obj.map((i) => {
return Object.keys(i).filter(y => y === 'name').map(key => {
return i['children'].length > 0 ? { [i[key]]: convert(i['children']) } : { [i[key]]: 'value' }
});
})
};
How to change my implementation for getting the right object?
Upvotes: 0
Views: 129
Reputation: 386680
You could build the entries from objects and map nested children, if exists.
const
transform = array => Object.fromEntries(array.map(({ name, children }) =>
[name, children.length ? [transform(children)] : 'value']
)),
data = { id: 1, name: "A", parent: null, children: [{ id: 2, name: "B", parent: 1, children: [] }, { id: 3, name: "C", parent: 1, children: [{ id: 4, name: "D", parent: 3, children: [] }] }] },
result = transform([data]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 3