Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.assign overrides original refereneces?

Tags:

javascript

I tried to "merge" two objects with Object.assign(), but somehow the original objects are overriden. See the example:

var x = {x:1};
var y = {y:2};

var z = Object.assign(x, y);

// what I've expected
console.log(z); // {"x": 1, "y": 2}

// what I haven't expected
console.log(x); // {"x": 1, "y": 2}
like image 806
ppasler Avatar asked Dec 07 '25 08:12

ppasler


1 Answers

An empty object must be provided as the first argument of Object.assign for a new merged object to be created.

var x = {
  x: 1
};
var y = {
  y: 2
};

var z = Object.assign({}, x, y);

// new object
console.log(z); // {"x": 1, "y": 2}

// still the same
console.log(x); // {"x": 1}
console.log(y); // {"y": 2}

You can read more information about Object.assign here.

like image 71
evolutionxbox Avatar answered Dec 08 '25 21:12

evolutionxbox