简体   繁体   English

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

[英]How to convert Data table to tree json format dynamically?

I'm using this data input to create a D3.js visualization: 我正在使用此数据输入来创建D3.js可视化文件:

Tree Layout 树布局

Okay so the right now my data input is a json file which i have hardcoded: 好的,现在我的数据输入是我已硬编码的json文件:

{
    "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. 我如何将该数据表动态转换为上述Json格式,我是否编写了一个解析数据表的函数以将其转换为上述格式,或者这是另一种方法。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM