serge
serge

Reputation: 15219

How does the Object.assign function work?

I would like to clone an object, on order to modify it and not affect the initial object.

let object1 = {
  a: 1,
  b: 2,
  c: 3
};

let object2 = Object.assign(object1);
object2.c = 999;

console.log(object1.c, object2.c);
// expected output: 3 999
// real output: 999 999

I suppose I don't correctly use the "assign" function...

Upvotes: 1

Views: 63

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386520

You need an empty object to assign the properties with Object.assign, because of

Object.assign(target, ...sources)
let object2 = Object.assign({}, object1);

let object1 = {
  a: 1,
  b: 2,
  c: 3
};

let object2 = Object.assign({}, object1);
object2.c = 999;

console.log(object1.c, object2.c);

Upvotes: 6

oma
oma

Reputation: 1894

Use Object.assign({}, object1) . the empty object will be cloned, so object1 will be added to the empty object.

Upvotes: 2

Related Questions