If we need to clone an object we can use the Object.assign method.

We can use this method to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

let obj1 = { a: 1, b: 2, c: 3 }; // Clone an object
let obj2 = Object.assign([], obj1);
console.log(obj2.a, obj2.b, obj2.c);
// expected output: 1 2 3 // Clone an object and add some other properties
let obj2 = Object.assign({c: 4, d: 5}, obj1);
console.log(obj2.a, obj.c, obj.d);
// expected output: 1 3 5 // Clone two object into another
let obj3 = { e: 6, f: 7 };
let obj4 = Object.assign(obj2, obj3);
console.log(obj4.a, obj4.b, obj4.c, obj4.d, obj4.e, obj4.f);
// expected output: 1 2 3 5 6 7

Laisser un commentaire