atr*_*ona 1 javascript arrays reactjs
我正在尝试获取嵌套数组的总和。数组结构是这样的:
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: [] }
]
Run Code Online (Sandbox Code Playgroud)
在这里您可以看到一个问题,然后是一个带有子问题的子数组。两者都有一个名为权重的键。我想将所有权重值计算为总和。
我正在使用这种方法
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')
Run Code Online (Sandbox Code Playgroud)
在这里,我可以从问题中获取权重值,但不能从子数组中获取权重值。就像上面的 arr 示例一样。我得到 sum = 30,但应该等于 85,我该如何解决这个问题。?
您可以采取递归方法。
const
sum = (array = [], key) => array.reduce(
(total, object) => total + object[key] + sum(object.child, key),
0
),
data = [{ 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: [] }],
result = sum(data, 'weightage');
console.log(result)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |