LudvigH
LudvigH

Reputation: 4737

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?

Upvotes: 0

Views: 416

Answers (3)

user663031
user663031

Reputation:

Although the same general idea as other answers, this might be slightly more readable:

arr.map(({a, b}) => ({a, b, c: a + b}))

Upvotes: 1

Dhiraj
Dhiraj

Reputation: 1462

you can use this

let arr2 = arr.map(x => {
      x.c = x.a + x.b;
      return x;
});

Please also refer working snippet

let arr = [ {a:1,b:2}, {a:3,b:6}];
let arr2 = arr.map(x => {
  return Object.assign({c : x.a + x.b},x);
});


console.log(arr);
console.log(arr2);
console.log(arr);

Upvotes: 1

Ry-
Ry-

Reputation: 224857

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

Upvotes: 3

Related Questions