-2

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));
copenndthagen
  • 46,750
  • 95
  • 274
  • 417
  • 1
    No. It doesn't work for circular objects and everything that contains non-plain objects or arrays. And it might not work for really large objects. – Bergi Jan 11 '21 at 05:37
  • But there is a solution how do it if circular exist. The question is understated in the status it makes no sense to answer – Daniil Loban Jan 11 '21 at 06:17

1 Answers1

0

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.
Mark
  • 939
  • 1
  • 7
  • 14