Saturday, March 10, 2018

Cloning Object in javascript

Last post , we have seen How object reference is working.But in some cases(very rare) if you want to copy exact object, means cloning, what you should do? How do you do that.

Its really a dull or tedious process.

Let see by code example,

let user = {
  name: "Kamal",
  age: 30
};

let clone = {}; // Going to clone into this empty object

// copy all properties from original into target
for (let key in user) {
  clone[key] = user[key];
}

console.log(clone);

Explanation: 

user is our original object and you have created one empty object called clone. After that , we have used for loop to iterate all the property of user object and assign the same to clone object. This loop will execute for all the properties of user. 

Checking with console log, all were copied to clone(target) object. Now you can modify your cloned object and check console. It will not affect user object. Since now cloned object is independent.

However, we have another simple way for cloning. Let see that too,

Object.assign:

Above we have used loop to iterate all the properties. So its look like some wide process. But using Object.assign() will make the process simpler.

Syntax is
Object.assign(destination[, src1, src2, src3...])

destination - Targeted object for clone
src1, src2,src3 etc., - Source object where you have to copy.

let user = { name: "Surya" };

let business = { businessType: "Cinema" };
let type = { isActor: true };

// copies all properties from business and type into user
Object.assign(user, business, type); console.log(user);

Output:
{name: "Surya", businessType: "Cinema", isActor: true}

Now everything is copied into our targeted user object.







No comments:

Post a Comment