所以我有一个像下面这样的树结构,我在叶子节点中有一个计数属性。我想总结计数并将计数总和与其父级相比较。比这样 parent1 和 parent2 有他们的孩子的总和。然后从那里继续,所以grantparent 有parent1 和parent2 的总和。我也有遍历树的功能。但是得到计数我无法得到。
有任何想法吗?
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);
}
}
}
树状结构
[
{
"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
}
]
}
]
}
]