I have an array of objects:
var myArray = [
{
"date" : "03/01/2017",
"value" : 2
}, {
"date" : "04/01/2017",
"value" : 6
}, {
"date" : "05/01/2017",
"value" : 4
}
];
I need to cumulate the value and keep the same array with updated values
The result would look like this
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)
}
];
I am aware that this exists
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
});
But I cannot find an example with object returning also objects
Use the this argument of Array.prototype.forEach
to accumulated the value - see demo below:
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;}
You can use map()
and Object.assign()
to make copy of objects.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With