Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add property to all objects in array [duplicate]

Tags:

javascript

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?

like image 740
Miguel Moura Avatar asked Apr 17 '16 14:04

Miguel Moura


People also ask

How do you add a property to all objects in an array?

We can use the forEach method to loop through each element in an object and add a property to each. We have the arr array. Then we call forEach with a callback that has the element parameter with the object being iterated through and we assign the b property to a value. according to the console log.

How do I add a key value to an array of objects?

To add a key/value pair to all objects in an array: Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.


2 Answers

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) })) 
like image 127
maioman Avatar answered Sep 29 '22 06:09

maioman


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));
like image 34
isvforall Avatar answered Sep 29 '22 07:09

isvforall