Skip to main content

Posts

Showing posts from April, 2017

JavaScript: Copy Object

For example, we have this Object : const myObject = { a: 1, b: 2, 3: 3 } And we want to clone it without affecting the original Object . We do not directly assign it ⚠️ const clonedObject = myObject Because every time the original myObject changes, the clonedObject will also follow the change and vice versa. It also applies to Array . We need to construct new Object and put the cloned content into it . Methods Deep Copy const myObject = { a: 1, b: 2, 3: 3 } const myClonedObject = JSON.parse(JSON.stringify(myObject)) This will work for nested-structured original Object . const myObject = { name: "Dilly the Photocopier", location: "Riverbank", specs: { status: "short circuited", model: "Xerox Aqua 3000" }, tags: ["office", "waterproof", "legend"] } // Deep clone using JSON method. const myClonedObject = JSON.parse(JSON.stringify(myObj...