Add property to all objects in array

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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)
}))

Solution 2 - Javascript

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));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiguel MouraView Question on Stackoverflow
Solution 1 - JavascriptmaiomanView Answer on Stackoverflow
Solution 2 - JavascriptisvforallView Answer on Stackoverflow