I am in the process of creating a tree structure, and I want it to be organized in the order of name, desc, then children. However, the JSON data I have received is not in this order. Is there a way to rearrange it efficiently or perhaps optimize the code considering multiple branches and potential additional elements being added to the input?
Below is the current code snippet:
var arry = [{
"name": "J",
"target": "L",
"desc": "2"
},
{
"name": "L",
"target": "A",
"desc": "1"
},
{
"name": "S",
"target": "L",
"desc": "3"
}
];
function toJSON(data) {
var root = data.find(function(x) {
return !data.some(function(y) {
return y.name === x.target
});
}).target;
console.log(root)
var desc = data.find(function(x) {
return !data.some(function(y) {
return y.name === x.target
});
}).desc;
var b = data.reduce(function(acc, x) {
acc[x.target] = acc[x.target] || [];
acc[x.target].push(x.name);
return acc;
}, {});
var tree = buildTree(root, b);
function buildTree(name, branches, desc) {
var tree = {
'name': name
};
if (branches[name]) {
tree.children = branches[name].map(function(x) {
return buildTree(x, branches, desc)
});
for (var child in branches[name]) {
var x = arry.find(function(i) {
return (i.name === branches[name][child] && i.target === name)
})
tree.children[child].desc = x.desc
}
}
return tree;
}
if (tree.name === root) {
tree.desc = root
}
for (var i in tree) {
console.log(i)
}
return tree;
} // JavaScript name code
var a = toJSON(arry)
console.log(JSON.stringify(a, null, 2))
The resulting output obtained is:
{
"name": "A",
"children": [
{
"name": "L",
"children": [
{
"name": "J",
"desc": "2"
},
{
"name": "S",
"desc": "3"
}
],
"desc": "1"
}
],
"desc": "A"
}
The desired result should be:
{
"name": "A",
"desc": "A",
"children": [
{
"name": "L",
"desc": "1",
"children": [
{
"name": "J",
"desc": "2"
},
{
"name": "S",
"desc": "3"
}
]
}
]
}