You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS如何计算嵌套数组对象内所有weightage属性值总和

嵌套数组指定属性递归求和问题修复

需求说明

需要对多层嵌套结构的数组做指定属性值累加,示例数组结构如下:外层为问题项,每个问题项通过child字段挂载子问题数组,外层项、子项均包含weightage权重字段,需要统计所有节点的weightage总和。

const arr = [
  { question: 'A', parentId: 1, weightage: 10, child: [] },
  {
    question: 'B',
    parentId: 4,
    weightage: 0,
    child: [{ id: 4, sub_question: 'X', weightage: 55 }]
  },
  { question: 'C', parentId: 5, weightage: 20, child: [] }
]

示例数组的正确累加结果为10 + 0 + 55 + 20 = 85。

原有代码问题

原有递归方法运行后仅返回30,只统计到了外层节点的权重值,代码如下:

const sum = (value, key) => {
  if (!value || typeof value !== 'object') return 0
  if (Array.isArray(value)) return value.reduce((t, o) => t + sum(o, key), 0)
  if (key in value) return value[key]
  return sum(Object.values(value), key)
}

const weightage = sum(arr, 'weightage')

问题根源:当代码检测到当前对象存在目标key时,会直接返回该key对应的值,终止当前对象剩余属性的递归遍历,导致挂载在child字段下的子节点完全没有进入统计逻辑。

修复后代码

调整对象节点的处理逻辑:检测到目标key存在时,先累加当前key的值,再继续递归遍历对象所有属性,保证深层嵌套节点也能被统计。

const sum = (value, key) => {
  if (!value || typeof value !== 'object') return 0
  if (Array.isArray(value)) return value.reduce((t, o) => t + sum(o, key), 0)
  // 先累计当前节点的目标属性值
  let total = key in value ? value[key] : 0
  // 继续递归遍历当前对象的所有属性,统计深层节点
  total += sum(Object.values(value), key)
  return total
}

const weightage = sum(arr, 'weightage')
console.log(weightage) // 输出85,结果符合预期

逻辑说明

  • 边界判断:传入值为假值、非对象类型时直接返回0,跳过原始值、null等无效节点
  • 数组处理:遍历数组每一项,递归累加单个数组项的求和结果
  • 对象处理:先统计当前节点自身的目标属性值,再递归遍历对象所有属性值,覆盖所有嵌套层级的节点,不会因为当前节点存在目标属性就终止遍历

内容的提问来源于stack exchange,提问作者atropa belladona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 06:48:15