gpt4 book ai didi

javascript 树结构 - 遍历树结构并显示子项内计数属性的总和

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:22:06 27 4
gpt4 key购买 nike

所以我有一个如下所示的树结构,其中我在叶节点中有一个计数属性。我想总结计数并将计数总和与其父项进行比较。比 parent1 和 parent2 有他们的 child 的总和。然后从那里继续,所以 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
}
]
}
]
}
]

最佳答案

您可以使用命名函数并再次为数组调用它。然后分配计数,如果没有给出则从 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com