Sometimes we want to clone an object in our JavaScript code.
In this article, we’ll look at how to clone an object with JavaScript.
Use the Object.assign Method
One way to clone a JavaScript object is to use the Object.assign
method.
For instance, we can write:
const obj = {
a: 1
};
const copy = Object.assign({}, obj);
console.log(copy);
We call Object.assign
with an empty object and obj
to copy the properties of obj
onto the empty object and return it.
Then copy
has the same content as obj
.
Use the Spread Operator
Another way to clone an object is to use the spread operator.
It works the same way as Object.assign
.
For example, we can use it by writing:
const obj = {
a: 1
};
const copy = {
...obj
};
console.log(copy);
Then we get the same result as the previous example.
Use the Lodash cloneDeep Method
If we need to deep clone an object, then we can use the Lodash cloneDeep
method to do the cloning.
It’ll clone properties at all levels instead of just the top level.
For instance, we can use it by writing:
const obj = {
a: 1
};
const copy = _.cloneDeep(obj);
console.log(copy);
Then copy
is a deep copy of obj
.
Conclusion
We can copy an object with the Object.assign
method or the spread operator.
To deep clone an object, we can use the Lodash cloneDeep
method.