javascript - 将最大值传播到嵌套树javascript中的父节点
问题描述
有一个嵌套数组,如下所示:
[
{
"id": 100,
"idParent": null,
"anidatedView": null,
"state": null,
"warningHighThreshold": null,
"dangerHighThreshold": null,
"lvl": 1,
"children": [
{
"id": 139,
"idParent": 100,
"anidatedView": null,
"state": null,
"warningHighThreshold": null,
"dangerHighThreshold": null,
"lvl": 2,
"children": [
{
"id": 186,
"idParent": 139,
"anidatedView": 279,
"state": 15.58,
"warningHighThreshold": 80,
"dangerHighThreshold": 100,
"lvl": 3,
"children": []
},
{
"id": 189,
"idParent": 139,
"anidatedView": 193,
"state": 40.65,
"warningHighThreshold": 80,
"dangerHighThreshold": 100,
"lvl": 3,
"children": []
}
]
},
{
"id": 140,
"idParent": 100,
"anidatedView": null,
"state": null,
"warningHighThreshold": null,
"dangerHighThreshold": null,
"lvl": 2,
"children": [
{
"id": 193,
"idParent": 140,
"anidatedView": 183,
"state": 65.41,
"warningHighThreshold": 92,
"dangerHighThreshold": 100,
"lvl": 3,
"children": []
}
]
},
{
"id": 141,
"idParent": 100,
"anidatedView": null,
"state": null,
"warningHighThreshold": null,
"dangerHighThreshold": null,
"lvl": 2,
"children": [
{
"id": 194,
"idParent": 141,
"anidatedView": 143,
"state": 60.77,
"warningHighThreshold": 90,
"dangerHighThreshold": 100,
"lvl": 3,
"children": []
},
{
"id": 195,
"idParent": 141,
"anidatedView": 436,
"state": 59.13,
"warningHighThreshold": 90,
"dangerHighThreshold": 100,
"lvl": 3,
"children": []
}
]
}
]
}
]
我正在尝试将状态的最大值(也是该最大节点的警告高阈值和危险高阈值)传播到所有父节点。
状态和阈值将始终在树的最后一级可用。
知道如何通过递归来做到这一点吗?
提前致谢!
解决方案
我终于设法解决了这个问题。我把我的解决方案留给那些可能有同样问题的人。
const populateState = item => {
if (item.children.length) {
const maxValue = item.children
.map(child => populateState(child))
.filter(({ state }) => state != null)
.reduce((maxValue, value) => (value.state > maxValue.state ? value : maxValue), { state: -1 })
item.state = maxValue.state
item.warningHighThreshold = maxValue.warningHighThreshold
item.dangerHighThreshold = maxValue.dangerHighThreshold
return maxValue
} else {
const { state, warningHighThreshold, dangerHighThreshold } = item
return { state, warningHighThreshold, dangerHighThreshold }
}
}
用法:(
数组变量是我在问题中定义的列表)
populateState({ children: array})
欢迎任何代码增强。
推荐阅读
- python - Redis 不启动队列中的作业
- javascript - 如何使用动态数据在高图中绘制堆积条形图?
- android - 添加到 ViewPager2 项目的 ItemDecoration 在项目布局的底部添加了不需要的空白
- css - Material-UI makeStyles 无法读取未定义的属性“向下”
- regex - 重定向到锚点
- laravel - 使用 PHPUnit 运行 Laravel 测试,排队的作业似乎总是在同步模式下运行。如何以标准模式调度它们?
- apache - htaccess - 删除 .php 扩展名并保留变量
- docker - 在 docker 中提供 DOCKER_HOST 变量后,找不到本地图像
- maven - 如何定义对第三方 jar 的特定包的依赖。我不想要 Jar 的所有包,只需要几个特定的包
- python - 我如何计算python每1.5秒的周期数?