js树形结构父节点等于直属子节点相加 求答案?
父节点的分数值socre等于直属子节点的score之和,只有最有一级节点的score有值,所以需要倒序求出每个父节点score的值,没想出来要怎么搞,求助大神的帮助
总结就是:3级加起来等于2级,2级加起来等于1级
let treeData = [{
level: "1",
parentCode: "0",
score: "",
setItemCode: "cdx10031",
setItemContent: "一级内容1",
sortNumber: 1,
children: [{
level: "2",
parentCode: "cdx10031",
score: "",
setItemCode: "cdx10061"
setItemContent: "二级内容1-1"
sortNumber: 1,
children: [{
level: "3",
parentCode: "cdx10061",
score: "1",
setItemCode: "cdx10090"
setItemContent: "三级级内容1-1-1"
sortNumber: 1,
},{
level: "3",
parentCode: "cdx10061",
score: "2",
setItemCode: "cdx10091"
setItemContent: "三级内容1-1-2"
sortNumber: 2,
}]
},{
level: "2",
parentCode: "cdx10031",
score: "",
setItemCode: "cdx10062"
setItemContent: "二级内容1-2"
sortNumber: 2,
children: [{
level: "3",
parentCode: "cdx10062",
score: "3",
setItemCode: "cdx10092"
setItemContent: "三级级内容1-2-1"
sortNumber: 1,
},{
level: "3",
parentCode: "cdx10062",
score: "4",
setItemCode: "cdx10093"
setItemContent: "三级内容1-2-2"
sortNumber: 2,
}]
}]
},{
level: "1",
parentCode: "0",
score: "",
setItemCode: "cdx10035",
setItemContent: "一级内容2",
sortNumber: 2,
children: [{
level: "2",
parentCode: "cdx10035",
score: "",
setItemCode: "cdx10065"
setItemContent: "二级内容2-1"
sortNumber: 1,
children: [{
level: "3",
parentCode: "cdx10065",
score: "1",
setItemCode: "cdx10095"
setItemContent: "三级级内容2-1-1"
sortNumber: 1,
},{
level: "3",
parentCode: "cdx10065",
score: "2",
setItemCode: "cdx10096"
setItemContent: "三级内容2-1-2"
sortNumber: 2,
}]
},{
level: "2",
parentCode: "cdx10035",
score: "",
setItemCode: "cdx10066"
setItemContent: "二级内容2-2"
sortNumber: 2,
children: [{
level: "3",
parentCode: "cdx10066",
score: "3",
setItemCode: "cdx10097"
setItemContent: "三级级内容2-2-1"
sortNumber: 1,
},{
level: "3",
parentCode: "cdx10066",
score: "4",
setItemCode: "cdx10098"
setItemContent: "三级内容2-2-2"
sortNumber: 2,
}]
}]
}]
回复
1个回答
test
2024-07-04
先算出二级的score,之后再算一级的score
level2Score(countyTargetData, {}, '3')
level2Score(countyTargetData, {}, '2')
function level2Score(tableArr, row, level) {
for (var i = 0; i < tableArr.length; i++) {
if (tableArr[i].level === level) {
row.score = Add(row.score, tableArr[i].score)
}
if (tableArr[i].children && tableArr[i].children.length > 0) {
if (tableArr[i].level * 1 + 1 === level * 1) {
tableArr[i].score = 0
}
level2Score(tableArr[i].children, tableArr[i], level)
}
}
}
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容