如何从普通数据结构构建树

时间:2015-05-29 10:48:03

标签: javascript recursion tree

我有以下数组包含对象:

var arr= [{id: "1", state: "1", ndi: "1558.3045298", children: "null"},
          {id: "2", state: "1", ndi: "1684.0732025", children: "null"},
          {id: "3", state: "1", ndi: "1809.8418752", children: "null"},
          {id: "4", state: "2", ndi: "1915.1603572", children: "null"},
          {id: "5", state: "2", ndi: "2023.5463678", children: "null"}]

如何获得state是儿童的根对象的对象树?

1 个答案:

答案 0 :(得分:0)

我猜你正在寻找组织整个阵列,因此项目是某些州的孩子。运行以下代码段以获取JSON序列化结果以进行检查(单击show code snippet以查看代码并运行它!):



var arr = [{
  id: "1",
  state: "1",
  ndi: "1558.3045298",
  children: "null"
}, {
  id: "2",
  state: "1",
  ndi: "1684.0732025",
  children: "null"
}, {
  id: "3",
  state: "1",
  ndi: "1809.8418752",
  children: "null"
}, {
  id: "4",
  state: "2",
  ndi: "1915.1603572",
  children: "null"
}, {
  id: "5",
  state: "2",
  ndi: "2023.5463678",
  children: "null"
}];

// This is going to hold states by id
var states = {};

// We iterate the array to get an organized by state children version
arr.forEach(function(item) {
  // If state by id object hasn't the id yet we create an state object
  // for current state id. There will be no duplicated states.
  if (!states.hasOwnProperty(item.state)) {
    states[item.state] = {
      id: item.state,
      children: []
    };
  }

  // We add the item to the state by id object
  states[item.state].children.push(item);


  // This re-defines the state property to point to the 
  // item's parent state
  item.state = states[item.state];

  // We drop this property from the item because it's
  // disturbing the new organized tree ;)
  delete item.children;
});

var alreadySerialized = [];

// The second argument is required to avoid cyclic object
// serialization.
// Learn more here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
document.getElementById("result").textContent = JSON.stringify(states, function(key, val) {
  if (val != null && typeof val == "object") {
    if (alreadySerialized.indexOf(val) >= 0) {
      return;
    }
    alreadySerialized.push(val);
  }
  return val;
});

<div id="result"></div>
&#13;
&#13;
&#13;

以下是转换后的结果数据示例:

{
   "1":{
      "id":"1",
      "children":[
         {
            "id":"1",
            "ndi":"1558.3045298"
         },
         {
            "id":"2",
            "ndi":"1684.0732025"
         },
         {
            "id":"3",
            "ndi":"1809.8418752"
         }
      ]
   },
   "2":{
      "id":"2",
      "children":[
         {
            "id":"4",
            "ndi":"1915.1603572"
         },
         {
            "id":"5",
            "ndi":"2023.5463678"
         }
      ]
   }
}