简体   繁体   中英

Convert array with tree structure to object in Javascript

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?

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; } 

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: {} } }

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM