clone an object in JavaScript?

 

As we know we can not directly assign an object to another variable. Because objects in JavaScript are references values, you can't simply just copy using the =

Also JavaScript does not have any default clone method to clone objects. So there are alternate ways to clone object using JavaScript.

const someObject = { key: 'value', key2: 'value2' }

1st:

newObject = Object.assign({}, someObject)

2nd:

newObject = JSON.parse(JSON.stringify(someObject))

Tags:

Share:

Related posts