Copy Object in Javascript
Copying Object in Javascript
There are three ways to copy object in Javascript
- spread (…) syntax
- Object.assign() function
- JSON.stringify() and JSON.parse() function
Spread Syntax
Spread syntax is the most simple way to shallow clone an object
1 | let book = {id:1, title: 'js tutorial'} |
Object.assign()
Object.assign() is also used to shallow clone an object.
1 | let book = {id:1, title: 'js tutorial'} |
Both spread and Object.assign copy/merge the properties from one object to another. They are shallow cloning object because when copying reference, they don’t copy the referenced data, only the reference itself.
So when the object to clone contains object, array or dates, shallow clone will cause both original and clone object use the same reference.
stringify and parse
JSON.stringify() and JSON.parse() methods are used to do deep clone. This works for all kind of objects containing objects, arrays and primitives.
Shallow clone example
1 | // Shallow Clone |
1 | // Deep Clone |