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
2
let book = {id:1, title: 'js tutorial'}
let cloneBook = {...book}

Object.assign()

Object.assign() is also used to shallow clone an object.

1
2
let book = {id:1, title: 'js tutorial'}
let cloneBook = Object.assign({}, book)

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
2
3
4
5
// Shallow Clone
let book = {id:1, title: 'js tutorial', details: {isbn: 100000 }}
let cloneBook = {...book}
cloneBook.details.isbn=22222
console.log(book) // the isbn is now 22222
1
2
3
4
5
// Deep Clone
let book = {id:1, title: 'js tutorial', details: {isbn: 100000 }}
let cloneBook = JSON.parse(JSON.stringify(book))
cloneBook.details.isbn=22222
console.log(book) // the isbn is still 100000

Reference