我有这个对象数组:
const data = [
{val: 40, color: 'red'},
{val: 5, color: 'green'},
{val: 55, color: 'lime'}
]
这是我想要得到的:
const result = [
{val: 40, color: 'red'},
{val: 45, color: 'green'},
{val: 100, color: 'lime'}
]
所以每一项都应该有相同的颜色和之前数据的累积值。
这是我的尝试:
const data = [
{val: 40, color: 'red'},
{val: 5, color: 'green'},
{val: 55, color: 'lime'}
]
// const result = [
// {val: 40, color: 'red'},
// {val: 45, color: 'green'},
// {val: 100, color: 'lime'}
// ]
const result = data.reduce((r, value, i) => {
const { val, color } = value
const cumVal = i === 0 ? val : r[i - 1].val
const newDatum = { val: cumVal, color }
return newDatum
}, data[0])
console.log(result)
错在哪里?为什么 r[i - 1]
未定义?
最佳答案
您的代码中有四个问题:
- 在这一行
const cumVal = i === 0 ? val : r[i - 1].val
你应该指定0
作为默认值,而不是val
- 在这一行
const newDatum = { val: cumVal, color }
中,您需要将val
添加到cumVal
- 作为初始值,您应该传递一个空数组,而不是您的
data
数组的第一个元素,因为您希望得到一个数组作为结果,而不是一个对象 - 您需要在每次迭代中返回
r
,而不是newDatum
- 同样,您希望最后有一个数组,而不是一个对象
这是一个固定版本:
const data = [
{val: 40, color: 'red'},
{val: 5, color: 'green'},
{val: 55, color: 'lime'}
]
// const result = [
// {val: 40, color: 'red'},
// {val: 45, color: 'green'},
// {val: 100, color: 'lime'}
// ]
const result = data.reduce((r, value, i) => {
const { val, color } = value
const cumVal = i === 0 ? 0 : r[i - 1].val
const newDatum = { val: val + cumVal, color }
r.push(newDatum);
return r;
}, [])
console.log(result)
关于javascript - 使用 reduce 对对象数组中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62897814/