JS: Clone, Deep Copy Object/Array

By Xah Lee. Date: . Last updated: .

Deep Copy

Here's the best way to clone (deep copy) a object. Object can be type Array or Object.

// deep copy/clone a object

// 2017-01-30 this is the best way. fastest too
const xah_deep_copy_array_or_object = (obj => JSON.parse ( JSON.stringify(obj) ) );

// test

let obj1 = {
"k1":1,
"k2":2,
};

let obj2 = {
"k3":3,
"k4":4,
"k5":obj1
};

console.log ( obj2 );
// { k3: 3, k4: 4, k5: { k1: 1, k2: 2 } }

console.log (
    xah_deep_copy_array_or_object( obj2 )
); // { k3: 3, k4: 4, k5: { k1: 1, k2: 2 } }

[see JS: JSON]

Shallow Copy

For shallow copy, use the slice method with no argument. This is same as clone if your array does not contain elements that are references (that is, other array or objects.).

const oldArray = [3,4,5];

// shallow copy
const newArray = oldArray.slice();

[see JS: Array.prototype.slice]

What's the Difference Between Deep Copy and Shallow Copy?

Shallow copy copies by reference of nested elements. This means, if you have shallow copy, changing a nested object may also change your copy.

// shallow copy isn't true clone

const mm = [8];

const aa = [3,mm];

// shallow copy
const bb = aa.slice();

mm[0] = 4;

// both are changed
console.log(aa); // [ 3, [ 4 ] ]
console.log(bb); // [ 3, [ 4 ] ]

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To
  6. Array Object
  7. Array.prototype

JS Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Prototype and Inheritance
  4. Create Object
  5. Object Literal Expression
  6. Create Object with Parent X
  7. Get/Set Prototype
  8. Prevent Adding Property
  9. Determine Type of Object
  10. Clone Object
  11. Test Object Equality
  12. Add Method to Prototype
  13. Object Object
  14. Object.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog