且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JSON对象转换为JSON树

更新时间:2023-01-15 23:07:09

好确定..我有评论这本是一个很好的问题,这是一个高兴地请一些思考过它。显然,这原来是比扁平化嵌套对象的数组更难了。

通过该算法不依赖于对象的id和阵列中的对象键之间的任何相关性的方式。与任何标识的对象可以是阵列中的任何地方。

\r
\r
  VAR的obj = {[ID:1,儿童:[2,4]数据:你好},{ID:2,儿童:[3],数据:我为第二个},{ID:3,儿童:[],数据:我为三},{ID:4 ,儿童:[6]数据:我为第四个},{ID:5,儿童:[],数据:我为十五},{ID:6,儿童:[],数据:我米第六届}];\r
\r
功能结构(平){\r
  功能巢(O){\r
    o.forEach(C => {如果(!c.child.length){//凉意从这里开始\r
                         c.child = c.child.map(E => flat.splice(flat.findIndex(F => f.id == E),1)[0]);\r
                         巢(c.child);\r
                         }\r
    });\r
  }\r
  巢(持平);\r
  返回持平;\r
}\r
\r
的document.write(< pre>中+ JSON.stringify(构造(OBJ),NULL,2)+< / pre>中);

\r

\r
\r
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 have convert 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 tree format of JSON based on child array of each property. How to approach the problem ?? How to code in javascript ??

Any help would appreciable. Thanks in advance.

Jsfiddle

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>");