So i have a tree stucture like below where i have a count attribute in the leaf nodes. i want to sum up the count and put the sum of counts against its parent. than so parent1 and parent2 have sum of their children. and than continue on from there, so grantparent has the sum of parent1 and parent2. i also have function to traverse the tree. But getting count i am unable to get.
Any ideas?
javascript
function transverse(element, result, isSegmentData) {
if (element instanceof Array){
element.forEach(function (item) {
{ transverse(item, result, isSegmentData); }
});
}
else if (element instanceof Object) {
if (element.hasOwnProperty("count")) {
// sum the count and provide to parent
}
if (element.hasOwnProperty("childNodes")) {
transverse(element.childNodes, result, isSegmentData);
}
}
}
tree structure
[
{
"nodeId": 66318,
"nodeName": "grand parent",
"childNodes": [
{
"nodeId": 66323,
"nodeName": "parent1",
"childNodes": [
{
"nodeId": 66324,
"nodeName": "child1",
"childNodes": [],
"count": 25
},
{
"nodeId": 66334,
"nodeName": "child2",
"childNodes": [],
"count": 85
},
{
"nodeId": 66439,
"nodeName": "child3",
"childNodes": [],
"count": 65
},
{
"nodeId": 66462,
"nodeName": "child4",
"childNodes": [],
"count": 954
}
]
},
{
"nodeId": 66323,
"nodeName": "parent2",
"childNodes": [
{
"nodeId": 66324,
"nodeName": "child1",
"childNodes": [],
"count": 225
},
{
"nodeId": 66334,
"nodeName": "child2",
"childNodes": [],
"count": 815
}
]
}
]
}
]