JavaScript How do you merge two objects with functions into a new one using ES6? merge objects with same key javascript,merge objects with spread

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!

Answer:1

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
    };
  }
}
Answer:2

Why does this code produce an array of 20 elements which are all undefined: > Array(20).map(function() { return 3; }) [ , , , , , , , , , , , , , , , , , , , ] Whereas this code produces an ...

Why does this code produce an array of 20 elements which are all undefined: > Array(20).map(function() { return 3; }) [ , , , , , , , , , , , , , , , , , , , ] Whereas this code produces an ...

Question Background: I'm learning AngularJS. I have created a simple app that takes in 3 form inputs, and on submission of this form a paginated list should be rendered. I have a dependancy on UI-...

Question Background: I'm learning AngularJS. I have created a simple app that takes in 3 form inputs, and on submission of this form a paginated list should be rendered. I have a dependancy on UI-...

I made a table that has checkboxes that show and hide rows to make it easier to compare specific rows. I wanted to add indeterminate checkboxes so that multiple rows can be selected or not selected at ...

I made a table that has checkboxes that show and hide rows to make it easier to compare specific rows. I wanted to add indeterminate checkboxes so that multiple rows can be selected or not selected at ...

I'm trying to crawl a webpage using Nightmare, but want to wait for #someelem to be present, only if it actually exists. Otherwise, I want Nightmare to move on. How can this be done using .wait()? I ...

I'm trying to crawl a webpage using Nightmare, but want to wait for #someelem to be present, only if it actually exists. Otherwise, I want Nightmare to move on. How can this be done using .wait()? I ...