Convert JSON object to JSON tree

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

I converted this object to

var newObj = [{
  id: 1,
  child: [{
    id: 2,
    child: [{
      id: 3,
      child: [],
      data: "I m third"
    }],
    data: "I m second"
  }, {
    id: 4,
    child: [{
      id: 6,
      child: [],
      data: "I m sixth"
    }],
    data: "I m fourth"
  }],
  data: "hello"
}, {
  id: 5,
  child: [],
  data: "I m fifth"
}];

which is nothing but a tree-like JSON format based on a child array of each property. How to approach the problem? How to code in javascript ??

Any help would be noticeable. Thanks in advance.

Jsfiddle

-5
source share
2 answers

A sentence with a temporary object for storing a link to elements.

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>');
Run codeHide result
+1
source

Well .. as I commented on this question, it was a good question, and it was nice to think about it a bit. Obviously, this is more complicated than smoothing an array of nested objects.

, - . id .

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>");
Hide result
+1

Source: https://habr.com/ru/post/1792494/


All Articles