How To Convert Data Table To Tree Json Format Dynamically?
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'
Solution 1:
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 = [];
constaddLeaf = (array) => {
if (!array || !array.length) return;
let temp = { name: array[0], children: [] };
if (array.length > 1) {
temp.children = [addLeaf(array.slice(1))];
}
return temp;
};
constaddToTree = (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))
Solution 2:
var test = newfunction() {
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();
Post a Comment for "How To Convert Data Table To Tree Json Format Dynamically?"