作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
所以我有一个如下所示的树结构,其中我在叶节点中有一个计数属性。我想总结计数并将计数总和与其父项进行比较。比 parent1 和 parent2 有他们的 child 的总和。然后从那里继续,所以 grantparent 有 parent1 和 parent2 的总和。我也有遍历树的功能。但是我无法得到计数。
有什么想法吗?
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
}
]
}
]
}
]
最佳答案
您可以使用命名函数并再次为数组调用它。然后分配计数,如果没有给出则从 child 那里获取计数。
var data = [{ "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 }] }] }];
data.reduce(function x(r, a) {
a.count = a.count || Array.isArray(a.childNodes) && a.childNodes.reduce(x, 0) || 0;
return r + a.count;
}, 0);
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript 树结构 - 遍历树结构并显示子项内计数属性的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39375531/
我是一名优秀的程序员,十分优秀!