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?
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.
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.
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) }))
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With