There are multiple ways to deep copy an object in JavaScript. In this shot, we will discuss two ways:
deepClone
methodJSON.parse
and JSON.stringify
methodsWhen 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
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
Free Resources