13

I want to mix two objects in JavaScript:

let a = {x: 1, y: 2, z:3};
let b = {x:10, y: 20};

let c = Object.assign(a, b);

This gives the correct value for c:

Object { x: 10, y: 20, z: 3 }

But now a has been modified too!

Object { x: 10, y: 20, z: 3 }

Is there a way to assign a onto b into a new object?

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245

4 Answers4

28

The first argument to assign is the target. So it's going to get changed. You can simply pass an empty object for your target if you don't want any of the sources to change:

let a = {x: 1, y: 2, z:3};
let b = {x:10, y: 20};

let c = Object.assign({},a, b);
console.log(c);
console.log(a);    // a is unchanged
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
13

You could use the spread operator:

let a = {x: 1, y: 2, z: 3};
let b = {x: 10, y: 20};

let c = {
  ...a,
  ...b
}

console.log(c);
console.log(a);
KevBot
  • 17,900
  • 5
  • 50
  • 68
  • The spread operator is a beautiful thing. Babel plugin: https://babeljs.io/docs/plugins/transform-object-rest-spread/ – sdgfsdh May 15 '17 at 10:06
4

Definitively the spread operator. It helps to add a single property, like styling CSS in JS. But be aware that it's currently only in stage 4 of EcmaScript.

const lessStyle = {
    color: 'blue',
    backgroundColor: 'yellow'
};

const moreStyle = {...lessStyle, color: 'red'};
// lessStyle is not affected

You can use it today in Typescript and JSX though.

Nicolas Zozol
  • 6,910
  • 3
  • 50
  • 74
0
let a = {x: 1, y: 2, z:3};
let b = {x:10, y: 20};

let c = Object.assign({}, a, b);

You need the {} within the assign method for the first object because if you read the documentation for Object.assign method here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Parameters It states that the first parameter is the target object and the rest are the sources. so right now you are assigning b to a and returning the new a to c. So if your first argument is an empty object this won't happen.

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
JoshG
  • 39
  • 7