Learnitweb

How to clone an object in JavaScript?

Here we are considering only shallow copy of objects. We are not considering deep cloning of objects. Following are the common ways of cloning object in JavaScript:

1. Object.assign() method

The Object.assign() method is used 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.

const source = {key1:1, key2:'Hello World'}
const const target={};
const clone = Object.assign(target, source);
console.log(source);
console.log(target);
console.log(clone);

Output

{key1: 1, key2: "Hello World"}
{key1: 1, key2: "Hello World"}
{key1: 1, key2: "Hello World"}

2. Spread Operator

It adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object. Note that Object.assign() triggers setters whereas spread syntax doesn’t.

var obj1 = {key1:1, key2:'Hello World'};
var clone = {...obj1};
console.log(clone);

Output

{key1: 1, key2: "Hello World"}

3. JSON stringify/parse

let clone = JSON.parse(JSON.stringify(objectToClone));

Note that JSON method will loose any Javascript types that have no equivalent in JSON. For example:

JSON.parse(JSON.stringify({a:null,b:NaN,c:Infinity,d:undefined,e:function(){},f:Number,g:false})) will generate {a: null, b: null, c: null, g: false}

Example:

var clone = JSON.parse(JSON.stringify({key1:1, key2: 'Hello World'}));
console.log(clone);

Output

{key1: 1, key2: "Hello World"}

4. Manually iterating properties of objects

You can write a function to iterate properties of an object and create a clone manually. Following is a basic function to create a function using this approach:

function fun(obj) {
    let cloneObject = {};
    for (let prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            cloneObject[prop] = obj[prop];
        }
    }
    return cloneObject;
}