Reputation: 8266
I have an array with the following format
let array = [{id: 1, desc: 'd1', children:[{id:1.1, desc:'d1.1', children:[]}]},
{id:2, desc:'d2', children:[] },
{id:3, desc:'d3', children:[] }];
Where each child is of the same time as the parent element. I would like it to transform it into an object with the format { [id]: {values} }
:
{
1: { id: 1, desc: 'd1', children: {1.1: {id:1.1, desc:'d1.1'}},
2: { id:2, desc:'d2' },
3: { id:3, desc:'d3' }
}
I tried in many ways but with no success. For instance:
let obj = array.map(a => mapArrayToObj(a));
mapArrayToObj = (e) => {
let obj = {[e.id]: e };
if(e.children.lenght > 0){
e.children = e.children.map(c => mapArrayToObj(c));
}
else{
return {[e.id]: e };
}
}
Is it even feasible in Javascript?
Upvotes: 2
Views: 830
Reputation: 122155
You could use reduce()
method to create recursive function and return object object as a result.
let array = [{id: 1, desc: 'd1', children:[{id:1.1, desc:'d1.1', children:[]}]}, {id:2, desc:'d2', children:[] }, {id:3, desc:'d3', children:[] }]
function build(data) {
return data.reduce(function(r, {id, desc, children}) {
const e = {id, desc}
if(children && children.length) e.children = build(children);
r[id] = e
return r;
}, {})
}
const result = build(array)
console.log(result)
Upvotes: 1
Reputation: 386883
You could use a recursive function which generates an object out of the given items without mutating the original data.
function getObjects(array) {
var object = {};
array.forEach(function (item) {
object[item.id] = Object.assign({}, item, { children: getObjects(item.children) });
});
return object;
}
var array = [{ id: 1, desc: 'd1', children: [{ id: 1.1, desc: 'd1.1', children: [] }] }, { id: 2, desc: 'd2', children: [] }, { id: 3, desc: 'd3', children: [] }];
console.log(getObjects(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 3
Reputation: 16364
Let's try with this code...
let array = [{id: 1, desc: 'd1', children:[{id:1.1, desc:'d1.1', children:[]}]},
{id:2, desc:'d2', children:[] },
{id:3, desc:'d3', children:[] }]
let object = {}
array.forEach(item => {
let children = item.children
object[item.id] = item
object[item.id].children = {}
children.forEach(child => {
object[item.id].children[child.id] = child
})
})
console.log(object)
Result:
{ '1': { id: 1, desc: 'd1', children: { '1.1': [Object] } },
'2': { id: 2, desc: 'd2', children: {} },
'3': { id: 3, desc: 'd3', children: {} } }
Upvotes: 1