我有一个对象数组:
var myArray = [
{
"date" : "03/01/2017",
"value" : 2
}, {
"date" : "04/01/2017",
"value" : 6
}, {
"date" : "05/01/2017",
"value" : 4
}
];
我需要累计值并使用更新的值保持相同的数组
结果看起来像这样
var myArray = [
{
"date" : "03/01/2017",
"value" : 2
}, {
"date" : "04/01/2017",
"value" : 8 //(2+6)
}, {
"date" : "05/01/2017",
"value" : 12 //(2+6+4)
}
];
我知道这存在
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
});
但是我找不到一个对象返回对象的例子
答案 0 :(得分:5)
使用Array.prototype.forEach
的此参数累积值 - 请参阅下面的演示:
var myArray=[{"date":"03/01/2017","value":2},{"date":"04/01/2017","value":6},{"date":"05/01/2017","value":4}];
myArray.forEach(function(e){
this.count = (this.count || 0) + e.value;
e.value = this.count;
},Object.create(null));
console.log(myArray);

.as-console-wrapper{top:0;max-height:100%!important;}

答案 1 :(得分:3)
您可以使用map()
和Object.assign()
复制对象。
var myArray = [{
"date": "03/01/2017",
"value": 2
}, {
"date": "04/01/2017",
"value": 6
}, {
"date": "05/01/2017",
"value": 4
}];
var result = myArray.map(function(o) {
var obj = Object.assign({}, o)
obj.value = this.total += o.value
return obj
}, {total: 0})
console.log(result)

答案 2 :(得分:2)
作为一个不同的示例并在var myArray = [
{
"date" : "03/01/2017",
"value" : 2
}, {
"date" : "04/01/2017",
"value" : 6
}, {
"date" : "05/01/2017",
"value" : 4
}
];
function accumulate() {
var count = 0;
return myArray.reduce(function(acc, cur) {
count += cur.value || 0;
cur.value = count;
acc.push(cur);
return acc;
}, []);
}
console.log(accumulate(myArray));
上回答您的问题,您将以这种方式使用reduce
{{1}}
答案 3 :(得分:1)
简单forEach
,可以在适当的位置改变数组。
var myArray = [
{
"date" : "03/01/2017",
"value" : 2
},
{
"date" : "04/01/2017",
"value" : 6
},
{
"date" : "05/01/2017",
"value" : 4
}
];
myArray.forEach(
(e,i,arr) => e.value += i && arr[i-1].value // only fires if i is truthy (i>0)
);
console.log(myArray);
.as-console-wrapper{top:0;max-height:100%!important;}