80

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?

0

2 Answers 2

87

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) })) 
Sign up to request clarification or add additional context in comments.

4 Comments

don't understand the DV either - both map and Number are preferred for stuff like this over forEach and + respectively.
OP wants c = b - a
@isvforall ok, thanks for the edit;
just to add a small detail, with the spread operator you still need to assign it to var r, the array array is not mutated.
50

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

7 Comments

shouldn't you try ES5 way
Are lambda expressions " =>" available in ES5?
@Miguel no, it's ES6, I edited with ES5 now
@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 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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.