I have the following array of objects:
var array = [ {'a': '12', 'b':'10'}, {'a': '20', 'b':'22'} ]; How can I add a new property c = b - a to all objects of the 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) })) map and Number are preferred for stuff like this over forEach and + respectively.c = b - avar r, the array array is not mutated.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));