There are a few ways to copy objects in javascript. One of them is using one of the native javascript object methods - Object.assign
const obj = {
name:"John",
surname:"Doe",
age:15
}
const copyObj = Object.assign({}, obj);
With ES6, you can also use the spread operator as well.
const obj = {
name:"John",
surname:"Doe",
age:15
}
const copyObj = {...obj}
However, these methods are for creating shallow copies.
Let's say you have a nested object and you use one of the methods mentioned above this is what will happen:
const obj = {
name:"John",
surname:"Doe",
age:19,
location:{
country:"USA",
city:"New York",
address:"Queens, New York 11418, USA",
}
}
const copyObj = {...obj}
obj.location.country = "Russia"
console.log(copyObj.location.country) //Russia
The nested objects will be copied as a reference, that means when you change some property of the nested object, it will also affect the copied object.
There are several ways to make a copy of nested object, one of them is:
const obj = {
name:"John",
surname:"Doe",
age:19,
location:{
country:"USA",
city:"New York",
address:"Queens, New York 11418, USA",
}
}
const copyObj = JSON.parse(JSON.stringify(obj));
obj.location.country = "Russia"
console.log(copyObj.location.country) //USA
Or using lodash's cloneDeep utility function:
import cloneDeep from 'lodash/cloneDeep'
const obj = {
name:"John",
surname:"Doe",
age:19,
location:{
country:"USA",
city:"New York",
address:"Queens, New York 11418, USA",
}
}
const copyObj = cloneDeep(obj)
You can find the original article here:
Copying objects in javascript
Top comments (0)