I have been struggling to create a tree array from the given JSON data. I have attempted to use filter, map, and reduce methods, but haven't been successful in achieving the desired result.
[{
"code": "2",
"name": "PENDING"
},{
"code": "2.2",
"name": "PENDING CHILDREN"
}, {
"code": "2.2.01.01",
"name": "PENDING CHILDREN CHILDREN"
}, {
"code": "2.2.01.02",
"name": "PENDING CHILDREN CHILDREN02"
}, {
"code": "1",
"name": "ACTIVE"
}, {
"code": "1.1",
"name": "ACTIVE CHILDREN"
}, {
"code": "1.1.01",
"name": "ACTIVE CHILDREN CHILDREN"
}]
However, I need to build this tree structure based on the code name provided.
[{
"code": "2",
"name": "PENDING",
"children": [{
"code": "2.2",
"name": "PENDING CHILDREN",
"children": [{
"code": "2.2.01.01",
"name": "PENDING CHILDREN CHILDREN"
}, {
"code": "2.2.01.02",
"name": "PENDING CHILDREN CHILDREN02"
}]
}]
},{
"code": "1",
"name": "ACTIVE",
"children": [{
"code": "1.1",
"name": "ACTIVE CHILDREN",
"children": [{
"code": "1.1.01",
"name": "ACTIVE CHILDREN CHILDREN"
}]
}]
}]
I have tried using reduce method, but I am having difficulty understanding how to implement this logic in JavaScript. Here is my code snippet:
var idToNodeMap = contas.reduce(function(map, node, i) {
map[node.code] = node;
node.children = [];
return map;
});