Open In App

How to copy properties from one object to another in ES6 ?

Improve
Improve
Like Article
Like
Save
Share
Report

The properties of one object can be copied into another object through different methods. Here are some of those methods.  

Object.assign(): By using the Object.assign() method, all enumerable properties of one or more source objects are copied to the target object. This method returns the modified target object. The properties of the target object are overwritten if they have the same key as properties in the sources. Properties from later sources overwrite properties from earlier sources. Object.assign() only copies enumerable and own properties from one object to another. As a result, it invokes getters and setters on the source and target. As a result, it assigns properties rather than copies or defines new ones. The merge sources may contain getters, thus making it unsuitable for merging new properties into prototypes.

Syntax:

Object.assign(target, ...sources)

 

Example:

JavaScript




<script>
    let obj1 = { a: 1, b: 2 };
    let obj2 = { a: 3, c: 4 };
    let obj3 = { b: 5, d: 6 };
    
    // Target object itself is changed.
    let targetobj1 = Object.assign(obj1, obj2);
    
    // Here the obj1 and targetobj1 both are same
    console.log(obj1);
    console.log(targetobj1);
    
    // Passing multiple objects and copy
    // to the target obj
    let targetobj2 = Object.assign(obj1, obj2, obj3);
    console.log(obj1);
    console.log(targetobj2);
</script>


Output:

{
    a: 3,
    b: 2,
    c: 4
}
{
    a: 3,
    b: 2,
    c: 4
}
{
    a: 3,
    b: 5,
    c: 4,
    d: 6
}
{
    a: 3,
    b: 5,
    c: 4,
    d: 6
}

Using Spread Operator: An array expression or string may have spread syntax (…) to expand where there are no or multiple arguments (for function calls) or elements (for array literals), or an object expression may be expanded where there are no or multiple key-value pairs (for object literals).

JavaScript




<script>
    let obj1 = { a: 1, b: 2 };
    let obj2 = { a: 3, c: 4 };
    let obj3 = { b: 5, d: 6 };
    
    // (...) is syntax of spread operator
    let targetobj = { ...obj1, ...obj2, ...obj3 };
    console.log(targetobj);
</script>
  


Output:

{
    a: 3,
    b: 5,
    c: 4,
    d: 6
}

By using for loop: It is necessary to iterate over the property of the source object (i.e. obj2) and assign the property with the value to target object obj1. But this method is limited to two objects if we use one for loop.

JavaScript




<script>
    let obj1 = { a: 1, b: 2 };
    let obj2 = { a: 3, c: 4 };
    for (let key in obj2) {
        obj1[key] = obj2[key];
    }
    console.log(obj1);
</script>


Output:

{
    a: 3,
    b: 2,
    c: 4
}


Last Updated : 26 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads