Adding fields to js objects, in functional way

I have an array of objects with a set of fields in node.js. Lets say

let arr = [ {a:1,b:2}, {a:3,b:6}]

I would like to extend all objects and assign to a new variable. My naïve approach is like the following way

let arr2 = arr.map(x => x.c = x.a + x.b )

However, the arrow function returns the x.a+x.b value, instead of the x object, so this won’t work as I hope. It also alters the arr in place which is very nonfunctional and confusing.

I’m relatively new to js so maybe I’m thinking wrong from the beginning. What is the idiomatic js expression for this kind of object extension?

Answer

You can write all properties from one object to another with Object.assign:

const arr2 = arr.map(x => Object.assign({c: x.a + x.b}, x));

And maybe at some point in the future with object spread (not yet standardized):

const arr2 = arr.map(x => ({...x, c: x.a + x.b}));

Leave a Reply

Your email address will not be published. Required fields are marked *