2

I want to join two objects with functions into a merged object using ES6, not sure how to do this.

For example, I'd like to merge these two objects:

const first = { first: function() { return { type: FIRST }; } }; const second = { second: function() { return { type: SECOND }; } }; 

Into a new object:

const new = { first: function() { return { type: FIRST }; }, second: function() { return { type: SECOND }; } } 

What is the best way to do this? I tried Object.assign({}, first, second); but this returned {}.

Any help would be appreciated!

2
  • Hey Rob, that might be the cause of my issue, good catch! Commented Apr 20, 2016 at 1:25
  • Note that new is a keyword and can't be used as an identifier. Sorry, brain fade on const. See MDN: Object.assign. ;-) Commented Apr 20, 2016 at 1:30

2 Answers 2

4

Your example should indeed work:

var joined = Object.assign({}, first, second); 

Be careful using assign without an empty object as the first parameter, such as:

var joined = Object.assign(first, second); 

Because first will be mutated.

JSBin example running your own code (and working):

https://jsbin.com/tekokawice/edit?js,console

Sign up to request clarification or add additional context in comments.

4 Comments

this is an excellent point, if you cannot or do not want to mutate the first object
Ya, absolutely - I guess it depends on the original authors intention - but technically both our answers could be right (depending on their requirements) :)
Agreed, thanks, I'll be adding the first parameter, I definitely don't want to mutate either object.
No worries. Possibly just a typo or something in your original snippet because it looks right
2

You should be able to use Object.assign for this:

Note as mentioned in Chris' answer below, this will mutate the first object.

JSBin example

var joined = Object.assign(first, second); // joined: { first: function first() { return { type: FIRST }; }, second: function second() { return { type: SECOND }; } } 

4 Comments

Thanks Jordan, I tried the Object.assign and for some reason was getting back {}, must have been a typo.
That modifies first, it doesn't create a new object (joined === first).
Unless I'm missing something...The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
to your edit, I mentioned that in the answer's second line

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.