Add property to all objects in the array

I have the following array of objects:

var array = [ {'a': '12', 'b':'10'}, {'a': '20', 'b':'22'} ]; 

How to add a new property c = b - a to all objects of the array?

+5
source share
2 answers

Use the forEach :

 var array = [{ 'a': '12', 'b': '10' }, { 'a': '20', 'b': '22' }]; array.forEach(function(e) { ec = +eb - +ea }); document.write(JSON.stringify(array)); 
+11
source

you can use array.map,

and you should use Number () to convert props to numbers to add:

 var array = [ {'a': '12', 'b':'10'}, {'a': '20', 'b':'22'} ]; var r = array.map( x => { xc = Number(xb) - Number(xa); return x }) console.log(r) 
+11
source

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


All Articles