copenndthagen
copenndthagen

Reputation: 50742

Javascript deep copy using JSON.parse and JSON.stringify

Is the below method a foolproof way of deep copying an object in Javascript i.e. even for very deeply nested objects/arrays ?

let newObj = JSON.parse(JSON.stringify(obj));

Upvotes: -1

Views: 3442

Answers (2)

sharad jain
sharad jain

Reputation: 1581

As metioned in other answer JSON methods to deep copy is unreliable with non primitive data types. In modern JS we can find new method called structuredClone() for deep copy.

var obj = {name: {firstName: 'John', lastName: 'Doe'}, age: 25 };

So to create copy of obj into obj1, We can do something like

var obj1 = structuredClone(obj);

Upvotes: 2

Mark Feng
Mark Feng

Reputation: 1009

In short, this is a simple but unreliable deep copy that works for simple JavaScript objects. But it would likely fail for some non-primitive data types' properties.

const set = new Set();
set.add(1);
set.add(2);

const map = new Map();
map.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})

const obj = {
  foo: () => 'bar',
  date: new Date(),
  undefined,
  set,
  map,
}

console.log(obj);

let unreliableNewObj = JSON.parse(JSON.stringify(obj));
console.log(unreliableNewObj); // some properties are lost, some properties are changed like set and map, can compare the result

// ES6 shallow copy that may help
let reliableNewObj = {
 ...obj,
}
console.log(reliableNewObj);

// 'real' deep copy from library
// https://lodash.com/docs#cloneDeep
let deepObj = _.cloneDeep(obj); // if _ is imported
console.log(deepObj)

For a reliable deep copy, alternatives are:

  • libraries like lodash
  • implement by ourselves, like this post, maybe quite complicated though.

Upvotes: 1

Related Questions