JavaScript clone objects can do Native deep cloning and shallow copy. A deep copy means that all of the values of the new variable are copied and disconnected from the original variable. A shallow copy means that certain (sub-)values are still connected to the original variable.
Using Spread syntax or Object.assign() or JSON parse you can do it.
Summarize the differences between the ways to clone an object in JavaScript:
Clone Method | Shallow/Deep | Clones nested objects/arrays | Copies object references | Copies object properties with object type |
---|---|---|---|---|
Object.assign() | Shallow | No | Yes | No |
Spread operator | Shallow | No | Yes | No |
JSON.stringify() + JSON.parse() | Deep | Yes | No | Yes |
Example JavaScript clone object
A simple example code clone an object using different techniques.
Using Spread syntax
Using spread will clone your object. Note this will be a shallow copy. However, the deeper objects are referenced.
<!DOCTYPE html>
<html>
<body>
<script>
const person = {
name: 'John',
age: 25,
}
// cloning the object
const clonePerson = { ... person}
console.log(clonePerson);
// changing the value of clonePerson
clonePerson.name = 'Peter';
console.log(clonePerson);
person.name = 'New';
console.log(person);
</script>
</body>
</html>
Output:
Using Object.assign()
It will also create a shallow copy of the object.
const person = {
name: 'John',
age: 25,
}
// cloning the object
const clonePerson = Object.assign({}, person);
console.log(clonePerson);
// changing the value of clonePerson
clonePerson.name = 'Peter';
console.log(clonePerson.name);
console.log(person.name);
Output:
{name: "John", age: 25} Peter John
Using JSON.parse()
This way will give you a deep copy.
const person = {
name: 'John',
age: 25,
}
// cloning the object
const clonePerson = JSON.parse(JSON.stringify(person));
console.log(clonePerson);
// changing the value of clonePerson
clonePerson.name = 'Peter';
console.log(clonePerson.name);
console.log(person.name);
Comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version