Add property to all objects in array

you can use array.map,

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

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

var r = array.map( x => {
  x.c = Number(x.b) - Number(x.a);
  return x
  })

console.log(r)

And, with the support of the spread operator, a more functional approach would be:

array.map(x => ({
    ...x,
    c: Number(x.a) - Number(x.b)
}))

Use forEach function:

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

array.forEach(e => e.c = +e.b - +e.a);
   
console.log(JSON.stringify(array));

Tags:

Javascript