I am given an array, links
:
const links = [
{parent: "flare", children: "analytics"} ,
{parent: "analytics", children: "cluster"} ,
{parent: "flare", children: "scale"} ,
{parent: "analytics", children: "graph"} ,
];
I want to make it into tree, like so:
const tree = {
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
},
{
"name": "graph",
}
]
}
]
};
Here is my attempt:
function buildTree(links) {
const map = { }
const findNodeInChildren = (name, obj) => {
if (obj[name]) {
return obj
} else if (!obj.children) {
return null
}
for (let i = 0; i < obj.children.length; i++) {
const found = findNodeInChildren(name, obj.children[i])
if (found) return found
}
return null
}
links.forEach(link => {
const foundNode = findNodeInChildren(link.parent, map)
if (!foundNode) {
const newNode = {
name: link.parent,
children: []
}
map[newNode.name] = newNode
} else {
foundNode[link.parent].children.push({
name: link.children,
children: []
})
}
})
return map
}
const links = [
{parent: "flare", children: "analytics"} ,
{parent: "analytics", children: "cluster"} ,
{parent: "flare", children: "scale"} ,
{parent: "analytics", children: "graph"} ,
];
const tree = buildTree(links)
const json = JSON.stringify(tree)
console.log(json)
Here’s the prettified JSON – it’s not working as intended:
{
"flare": {
"name": "flare",
"children": [
{
"name": "scale",
"children": []
}
]
},
"analytics": {
"name": "analytics",
"children": [
{
"name": "graph",
"children": []
}
]
}
}
What is going wrong?