问题
I'm using this data input to create a D3.js visualization:
Tree Layout
Okay so the right now my data input is a json file which i have hardcoded:
{
    "name":"Fun",
    "children": [
        {
            "name": "Legal",
            "children": [
                { "name": "Adventure" },
                { "name": "Movie" },
                { "name": "M&m" }
            ]
        },
        {
            "name": "frowned upon",
            "children": [
                { "name": "recreational stuff" },
                { "name": "religious views" }
            ]
        }
    ]
}
But my data input is actually :
How do i convert this data table dynamically to the above mentioned Json format, do i write a function which parses the data table to convert it into the above format or this is there another way.
回答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();
回答2:
You can write recursive function to restructure data.
const a = [[
  'fun', 'legal', 'adventure',
], [
  'fun', 'legal', 'movie',
], [
  'fun', 'legal', 'm&m'
], [
  'fun', 'frowned upon', 'rec stuff'
], [
  'fun', 'frowned upon', 'religius views'
]];
let t = [];
const addLeaf = (array) => {
  if (!array || !array.length) return;
  let temp = { name: array[0], children: [] };
  if (array.length > 1) {
    temp.children = [addLeaf(array.slice(1))];
  }
  return temp;
};
const addToTree = (tree, array) => {
  if (!array || !array.length) return [];
  const branchIndex = tree.findIndex(entry => entry.name === array[0]);
  if (branchIndex !== -1) {
    tree[branchIndex].children = [...addToTree(tree[branchIndex].children, array.slice(1))];
  } else {
    tree = [...tree, addLeaf(array)];
  }
  return tree;
};
a.forEach((entry) => {
  t = addToTree(t, entry);
});
console.log(JSON.stringify(t, null, 2))
来源:https://stackoverflow.com/questions/53313396/how-to-convert-data-table-to-tree-json-format-dynamically