Skip to content Skip to sidebar Skip to footer

Javascript Array Of Object To Tree Structure

I have an array of objects like this.. var obj_1 = {id:1, text:'Title 1', checked: false, unitId:0, line: 0}; var obj_2 = {id:2, text:'Title 1.1', checked: false, unitId:1, line: 0

Solution 1:

something along the lines

var obj_1 = {id:1, text:"Title 1", checked: false, unitId:0, line: 0};
var obj_2 = {id:2, text:"Title 1.1", checked: false, unitId:1, line: 0};
var obj_3 = {id:3, text:"Title 1.2", checked: false, unitId:1, line: 1};
var obj_4 = {id:4, text:"Title 1.1.1", checked: false, unitId:0, line: 1};
var obj_5 = {id:5, text:"Title 2", checked: false, unitId:0, line: 1};

var obj_list = [obj_1,obj_2,obj_3,obj_4,obj_5];
let result = obj_list.reduce((acc,o)=>{
    let unitId = o.unitId;
    let cur = acc[unitId];
    if(!cur){
        cur = {checked:false, text: `Unit ${unitId + 1}`, children:[]};
        acc[unitId] = cur;
    }
    cur.children.push(o);
    return acc;
},{});
result = Object.values(result).map(v=>{
    let dic = v.children.reduce((acc, o)=>{
        let lineId = o.line;
        let cur = acc[lineId];
        if(!cur){
            cur = {checked:false, text: `Line ${String.fromCharCode(lineId+65)}`, children:[]};
            acc[lineId] = cur;
        }
        cur.children.push(o);
        return acc;
    },{})
    v.children = Object.values(dic);
    return v;
})

result = {text:'Main Root', checked:false, children:result}
console.log(JSON.stringify(result,null,2))

Post a Comment for "Javascript Array Of Object To Tree Structure"