Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to deep copy in JavaScript

Nouman Abbasi

There are multiple ways to deep copy an object in JavaScript. In this shot, we will discuss two ways:

  1. Using the lodash deepClone method
  2. Using JSON.parse and JSON.stringify methods

lodash deepClone

When you deep copy an object in JavaScript, your best bet is to use an existing method from a library. The deepClone method in lodash can be used to easily deep clone an object.

import _ from 'lodash';

var original = [{ 'a': 1 }, { 'b': 2 }];
 
var copy = _.cloneDeep(original);
console.log(copy)
console.log(copy[0] === original[0]); // false as different objects now

JSON.parse and JSON.stringify

If your object is not too complex, you can use the JSON.parse and JSON.stringify methods to make a deep copy.

This method will not work if the object consists of Dates, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays, or other complex types.

var original = [{ 'a': 1 }, { 'b': 2 }];
 
var copy = JSON.parse(JSON.stringify(original));
console.log(copy)
console.log(copy[0] === original[0]); // false as different objects now

RELATED TAGS

javascript

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring