Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an immutable version of Object.assign?

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?

like image 321
sdgfsdh Avatar asked Jul 27 '16 15:07

sdgfsdh


2 Answers

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
like image 92
Matt Burland Avatar answered Sep 21 '22 16:09

Matt Burland


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);
like image 43
KevBot Avatar answered Sep 20 '22 16:09

KevBot