76

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?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

2 Answers2

84

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)
}))
maioman
  • 18,154
  • 4
  • 36
  • 42
48

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));
isvforall
  • 8,768
  • 6
  • 35
  • 50
  • shouldn't you try ES5 way – Mritunjay Apr 17 '16 at 14:30
  • Are lambda expressions " =>" available in ES5? – Miguel Moura Apr 17 '16 at 14:30
  • @Miguel no, it's ES6, I edited with ES5 now – isvforall Apr 17 '16 at 14:31
  • 4
    @Mritunjay I think if the OP can't be bothered to _try_ to solve the problem themself they should accept the answers they get, whether ES5 or ES6. – Andy Apr 17 '16 at 14:34
  • @Andy I agree, but I would say if it's not asked I would prefer being answered in ES5 way only. There are a lot of people who will view answers and might get confused. – Mritunjay Apr 17 '16 at 14:42
  • But then we could have worked out what version to use if some code had been presented to us. The onus is on the asker to provide the details and not the rest of us to read their minds. The OP has enough rep to know how this site works by now, and this question wasn't a good one. – Andy Apr 17 '16 at 14:47
  • I think this was a good question -- I had the same question just today (in 2021). But, I agree that the OP should have at least posted what code he/she tried. – Eric Hepperle - CodeSlayer2010 Nov 27 '21 at 20:31