JavaScript - assign() method

revision:


Category : object

The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

Syntax :

        Object.assign(target, ...sources)
    

Parameters:

target : required. The target object — what to apply the sources' properties to, which is returned after it is modified.

source : the source object(s) — objects containing the properties you want to apply.

Examples:

        const target = { a: 1, b: 2 };
        const source = { b: 4, c: 5 };
        const returnedTarget = Object.assign(target, source);
        console.log(target);
        // Expected output: Object { a: 1, b: 4, c: 5 }
        console.log(returnedTarget === target);
        // Expected output: true
    

Practical examples

example: cloning an object

code:
                    <div>
                        <p id="assign-1"></p>
                        <p id="assign-2"></p>
                    
                    </div>
                    <script>
                        const obj = { a: 1 };
                        document.getElementById("assign-1").innerHTML = "object : " + JSON.stringify(obj);
                        const copy = Object.assign({}, obj);
                        console.log(copy); // { a: 1 }
                        document.getElementById("assign-2").innerHTML = "object copy: " + JSON.stringify(copy);
                    </script>
                

example: copy an object

code:
                    <div>
                        <p id="assign-3"></p>
                        <p id="assign-4"></p>
                        <p id="assign-5"></p>
                        <p id="assign-6"></p>
                        <p id="assign-7"></p>
            
                    </div>
                    <script>
                    const object1 = {  a: 1,  b: 2, c: 3 };  
                        const object3= {  g: 1,  h: 2, i: 3 };    
                        const object2 = Object.assign({c: 4, d: 5}, object1);  
                        const object4 = Object.assign({g: 34, h: 25}, object3);  
                        console.log(object2.c, object2.d);  
                        console.log(object4.g, object4.h);  
                        document.getElementById("assign-3").innerHTML = "object2.c: " + (object2.c);
                        document.getElementById("assign-4").innerHTML = "object2.d: " + (object2.d);
                        document.getElementById("assign-5").innerHTML = "object4.g: " + (object4.g);
                        document.getElementById("assign-6").innerHTML = "object4.h: " + (object4.h);
            
                    </script>