In this post, you’ll find 3 easy ways to perform shallow clone (aka copy) of objects in JavaScript.
As a bonus, I’m going to show how you can also update, add, or remove properties in place on the clone. That’s useful when you want to perform an update on the object in an immutable manner.
The 3 ways to clone objects described in this post perform shallow copy.
A shallow copy means that only the actual object gets copied. If the copied object contains nested objects — these nested objects aren’t get cloned.
The simplest way to clone a plain JavaScript object is to invoke the object spread operator:
const clone = {
...object
};
Where object
is the object you’d like to copy, and clone
is the shallow copy of object
.
For example, let’s create a shallow copy of hero
object:
const hero = {
name: 'Batman',
city: 'Gotham'
};
const heroClone = {
...hero
};
heroClone; // { name: 'Batman', city: 'Gotham' }
hero === heroClone; // => false
heroClone
is a clone object of hero
, meaning that it contains all the properties of hero
.
hero === heroClone
evalutes to false
— hero
and heroClone
are, nevertheless, difference object instances.
An immediate benefit of using object spread is that you can update or add new properties to the cloned object in place if you need it.
Let’s clone the hero
object, but update name
property to a different value and add a new property realName
:
const hero = {
name: 'Batman',
city: 'Gotham'
};
const heroEnhancedClone = {
...hero,
name: 'Batman Clone',
realName: 'Bruce Wayne'
};
heroEnhancedClone;
// { name: 'Batman Clone', city: 'Gotham', realName: 'Bruce Wayne' }
#object #javascript #programming