Javascript cumulates an object array for an object array

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 copy the value and keep the same array with updated values

The result will 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 know it exists

 [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { return accumulator + currentValue; }); 

But I cannot find an example with an object returning objects as well

+6
source share
4 answers

Use this Array.prototype.forEach argument to accumulate the value - see the 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;} 
+5
source

You can use map() and Object.assign() to copy 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) 
+3
source

As another example and answer to your question in .reduce() , you should use shorthand this way

 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)); 
+2
source

A simple forEach that mutates an array in place.

 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;} 
+1
source

Source: https://habr.com/ru/post/1013754/


All Articles