如何将数据表动态转换为树json格式?

时间:2018-11-15 06:07:44

标签: javascript json d3.js data-visualization

我正在使用此数据输入来创建D3.js可视化:

Tree Layout

好的,现在我的数据输入是我已硬编码的json文件:

{
    "name":"Fun",
    "children": [
        {
            "name": "Legal",
            "children": [
                { "name": "Adventure" },
                { "name": "Movie" },
                { "name": "M&m" }
            ]
        },
        {
            "name": "frowned upon",
            "children": [
                { "name": "recreational stuff" },
                { "name": "religious views" }
            ]
        }
    ]
}

但是我的数据输入实际上是:

Data table input

如何将数据表动态转换为上述Json格式,我是否编写了一个解析数据表以将其转换为以上格式的函数,或者这是另一种方法。

2 个答案:

答案 0 :(得分:3)

您可以编写递归函数来重组数据。

Restangular

答案 1 :(得分:1)

var test = new function() {

  var table = [
    ['fun', 'legal', 'adventure'],
    ['fun', 'legal', 'mvie'],
    ['fun', 'legal', 'M&M'],
    ['fun', 'Frowned upon', 'Rec stuff'],
    ['fun', 'Frowned upon', 'Regligious views']
  ];

  var res = [];

  this.init = function() {
    for (var i = 0; i < table.length; i++) {
      var curRow = table[i];
      test.myAddFun(res, curRow, 0);
    }
    console.log(res);
  };

  this.myAddFun = function(_res, arr, startIndex) {
    var addedToJSON = false;
    for (var i = 0; i < _res.length; i++) {
      var curJSON = _res[i];
      if (curJSON['name'] == arr[startIndex]) {
        if (startIndex < arr.length - 1) {
          test.myAddFun(curJSON['children'], arr, startIndex + 1);
        }
        addedToJSON = true;
        break;
      }
    }
    if (addedToJSON) {
      return;
    }
    var curJSON = {};
    curJSON['name'] = arr[startIndex];
    if (startIndex < arr.length - 1) {
      curJSON['children'] = [];
      test.myAddFun(curJSON['children'], arr, startIndex + 1);
    }
    _res.push(curJSON);
    return;
  };

};
test.init();