0

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?

3 Answers 3

3

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

1 Comment

Nice! Exactly what I hoped for! :D
1

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

1 Comment

Sorry. This will overwrite arr, :(
1

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

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

1 Comment

mhm i like this one ^_^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.