How to duplicate Javascript object properties in another object?

JavascriptFront End TechnologyObject Oriented Programming

The Object.assign() method can be used to copy the values of all of the object's own properties(enumerable only) from one or more source objects to a target object.

For example, to copy all the properties of a source object onto a target object, you can use the following code −

Example

const targetObj = { a: 1, b: 2 };
const sourceObj = { b: 4, c: 5 };
const returnedTarget = Object.assign(targetObj, sourceObj);
console.log(targetObj);
console.log(returnedTarget);
console.log(returnedTarget === targetObj);
console.log(sourceObj);

Output

{ a: 1, b: 4, c: 5 }
{ a: 1, b: 4, c: 5 }
true
{ b: 4, c: 5 }

Note 

  • sourceObj did not change.

  • returnedTarget and targetObj are the same.

  • The Object.assign() method only copies enumerable and own properties from a source object to a target object.It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters.

raja
Published on 17-Sep-2019 12:26:59
Advertisements