从索引创建父子嵌套JSON

时间:2017-07-05 06:16:24

标签: javascript jquery d3.js parent-child

我是D3的新手。我正在使用d3.jd版本3。 我有以下类型的JSON:

[
  {
    "health": "OK",
    "name": "new A",
    "index": "A"
  },
  {
    "health": "SEVERE",
    "name": "new AB",
    "index": "A > B"
  },
  {
    "health": "OK",
    "name": "new ABC",
    "index": "A > B > C"
  },
  {
    "health": "OK",
    "name": "new ADE",
    "index": "A > D > E"
  },
  {
    "health": "SEVERE",
    "name": "new AD",
    "index": "A > D"
  }
]

我想从JSON上面创建以下父子嵌套数据:

[
  {
    "health": "OK",
    "name": "new A",
    "index": "A",
    "children": [
      {
        "health": "SEVERE",
        "name": "new AB",
        "index": "A > B",
        "children": [
          {
            "health": "OK",
            "name": "new ABC",
            "index": "A > B > C"
          }
        ]
      },
      {
        "health": "SEVERE",
        "name": "new AD",
        "index": "A > D",
        "children": [
          {
            "health": "OK",
            "name": "new ADE",
            "index": "A > D > E"
          }
        ]
      }
    ]
  }
]

我想通过索引创建父子数据。 那么,如果索引是" A> B"和" A"是父母和" B"是孩子。

这只是我没有的样本数据。大数据。所以,想要提高表现。

可以用d3或jquery创建嵌套的父子JSON表单对象数组吗?

1 个答案:

答案 0 :(得分:0)

我做到了。对于它我需要添加父ID。



var data = [
  {
    "health": "OK",
    "name": "new A",
    "index": "A"
  },
  {
    "health": "SEVERE",
    "name": "new AB",
    "index": "A > B"
  },
  {
    "health": "OK",
    "name": "new ABC",
    "index": "A > B > C"
  },
  {
    "health": "OK",
    "name": "new ADE",
    "index": "A > D > E"
  },
  {
    "health": "SEVERE",
    "name": "new AD",
    "index": "A > D"
  }
]

  function fnGetParentID(index) {
                     var indexArr = index.split(' > ');
                     var parentIndex = '';
                     if(indexArr.length !== 1){
                         parentIndex = index.replace(" > " + indexArr[indexArr.length - 1], '')
                     }
                     return parentIndex;
                 };

 function fnCreateStrunture(f) {
                    return f.sort(function (a, b) {
                        return a.index.length < b.index.length ? 1 : a.index.length == b.index.length ? a.index < b.index ? -1 : 1 : -1;
                    }).reduce(function (p, c, i, a) {
                        c.ParentID = fnGetParentID(c.index);
                        var parent = !!c.ParentID && a.find(function (e) {
                                return e.index === c.ParentID;
                            });
                        !!parent ? !!parent.children && parent.children.push(c) || (parent.children = [c]) : p.push(c);
                        return p;
                    }, []);
                };
                           
var nestedJson = fnCreateStrunture(data);

document.getElementById("nested").innerHTML = JSON.stringify(nestedJson, undefined, 2);
&#13;
<pre id="nested"></pre>
&#13;
&#13;
&#13;