convert JSON object to JSON tree

后端 未结 2 1033
余生分开走
余生分开走 2021-01-17 09:21
var obj = [{
    id: 1,
    child:[2,4],
    data : \"hello\"
},{
    id: 2,
    child:[3],
    data : \"I m second\"
},
{   
    id: 3,
    child:[],
    data : \"I         


        
相关标签:
2条回答
  • 2021-01-17 09:34

    Well ok.. as i have commented this one was a good question and it was a pleasure to give some thinking over it. Obviously this turns out to be harder than flattening an array of nested objects.

    By the way the algorithm doesn't rely on any correlation between the object's ids and the objects keys in the array. An object with any id can be anywhere in the array.

    var obj = [{ id: 1, child: [2, 4], data: "hello" }, { id: 2, child: [3], data: "I m second" }, { id: 3, child: [], data: "I m third" }, { id: 4, child: [6], data: "I m fourth" }, { id: 5, child: [], data: "I m fifth" }, { id: 6, child: [], data: "I m sixth" }];
    
    function construct(flat){
      function nest(o) {
        o.forEach( c => { if (!!c.child.length) { // coolness starts here
                             c.child = c.child.map( e => flat.splice(flat.findIndex( f => f.id == e),1)[0]);
                             nest(c.child);
                             }
        	            });
      }
      nest(flat);
      return flat;
    }
    
    document.write("<pre>" + JSON.stringify(construct(obj), null, 2) + "</pre>");

    0 讨论(0)
  • 2021-01-17 09:49

    A proposal with a temporary object for keeping the reference to the items.

    var array = [{ id: 1, child: [2, 4], data: "hello" }, { id: 2, child: [3], data: "I m second" }, { id: 3, child: [], data: "I m third" }, { id: 4, child: [6], data: "I m fourth" }, { id: 5, child: [], data: "I m fifth" }, { id: 6, child: [], data: "I m sixth" }],
        tree = [];
    
    array.forEach(function (a) {
        if (!this[a.id]) {
            this[a.id] = { id: a.id };
            tree.push(this[a.id]);
        }
        this[a.id].data = a.data;
        this[a.id].child = a.child.map(function (b) {
            this[b] = this[b] || { id: b };
            return this[b];
        }, this);
    }, Object.create(null));
    
    document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');

    0 讨论(0)
提交回复
热议问题