Reputation: 8460
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!
Upvotes: 2
Views: 70
Reputation: 13896
You should be able to use Object.assign for this:
Note as mentioned in Chris' answer below, this will mutate the first object.
var joined = Object.assign(first, second);
// joined:
{
first: function first() {
return {
type: FIRST
};
},
second: function second() {
return {
type: SECOND
};
}
}
Upvotes: 2
Reputation: 58292
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
Upvotes: 4