如何动态地将数据表转换为树json格式? [英] How to convert Data table to tree json format dynamically?
本文介绍了如何动态地将数据表转换为树json格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用此数据输入来创建D3.js可视化:
如何将数据表动态转换为上述Json格式,我是否编写了一个解析数据表以将其转换为上述格式的函数,或者这是另一种方法.
解决方案
var test = new function(){var table = [['fun','legal','adventure'],['fun','legal','mvie'],['fun','legal','M& M'],['fun','Frowned','Rec stuff'],[有趣",着迷",宗教观点"]];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){varAddedToJSON = False;for(var i = 0; i< _res.length; i ++){var curJSON = _res [i];如果(curJSON ['name'] == arr [startIndex]){如果(startIndex< arr.length-1){test.myAddFun(curJSON ['children'],arr,startIndex + 1);}addToJSON = true;休息;}}如果(addToToJSON){返回;}var curJSON = {};curJSON ['name'] = arr [startIndex];如果(startIndex< arr.length-1){curJSON ['children'] = [];test.myAddFun(curJSON ['children'],arr,startIndex + 1);}_res.push(curJSON);返回;};};test.init();
I'm using this data input to create a D3.js visualization:
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.
解决方案
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();
这篇关于如何动态地将数据表转换为树json格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文