The Object.assign()
method copies all the enumerable properties of the given objects to a single object and returns it.
Example
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const obj3 = { c: 3 };
// combine all the properties of
// obj1, obj2, obj3 into a single object
const mergedObj = Object.assign(obj1, obj2, obj3);
console.log(mergedObj);
// Output: { a: 1, b: 2, c: 3 }
assign() Syntax
The syntax of the assign()
method is:
Object.assign(target, ...sources)
Here, assign()
is a static method. Hence, we need to access the method using the class name, Object
.
assign() Parameters
The assign()
method takes in:
- target - the target object to which we will copy all the properties of the sources.
- sources - the source object(s) whose properties we want to copy.
assign() Return Value
The assign()
method returns the target object.
Note: Properties in the target object are overwritten by properties in the sources if they have the same key.
Example 1: Javascript Object.assign() to Clone Objects
// create source object
const obj = {
name: "Alan Turing",
age: 20,
};
// create target object
let newObject = {};
// copy enumerable properties of obj to newObject
// newObject is returned and stored in copy object
const copy = Object.assign(newObject, obj);
// print the copy object
console.log(copy);
// Output: { name: 'Alan Turing', age: 20 }
// print newObject
console.log(newObject);
// Output: { name: 'Alan Turing', age: 20 }
In the above example, we have used the assign()
method to assign the contents of obj to newObject.
Since assign()
modifies the target object and returns the same object, both copy and newObject are clones of one another. As a result, we get identical outputs when we print them both.
Example 2: assign() to Merge Objects
// source objects
const o1 = { a: 1, b: 2, c: 3 };
const o2 = { b: 12, c: 13 };
const o3 = { c: 23 };
// merge o1, o2, and o3
// earlier source keys are overwritten by later sources
const o4 = Object.assign({}, o1, o2, o3);
console.log(o4);
// Output: { a: 1, b: 12, c: 23 }
In the above example, we have used assign()
to merge the objects o1, o2, and o3 into a new object o4.
const o4 = Object.assign({}, o1, o2, o3);
Using the empty object {}
as a target object ensures that the properties of the other objects are copied to a new object without modifying any of the source objects.
As can be seen from the output, properties of later objects overwrite that of earlier ones. For example,
- the
b
key from o1 is overwritten by its counterpart in o2. - the
c
keys from o1 and o2 are overwritten by their counterpart in o3.
Note: If the source value is a reference to an object, it only copies the reference value.
Recommended Reading: