Mark Kadlec
Mark Kadlec

Reputation: 8460

How do you merge two objects with functions into a new one using ES6?

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

Answers (2)

omarjmh
omarjmh

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.

JSBin example

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

// joined:

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

Upvotes: 2

Chris
Chris

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

Related Questions