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 Object]

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 ] ]

Array Topic

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

  1. JS: Array Object
  2. JS: Array.prototype

Object and Inheritance Topic

  1. JS: Object System Overview
  2. JS: What's Object?
  3. JS: Prototype and Inheritance
  4. JS: Create Object
  5. JS: Object Literal Expression
  6. JS: Find Object's Prototype
  7. JS: Set Object's Prototype
  8. JS: How to Create Object with Parent X?
  9. JS: Prevent Adding Property
  10. JS: Determine Type of Object
  11. JS: Primitive Value Object Wrapper
  12. JS: Clone, Deep Copy Object/Array
  13. JS: Test Equality of Objects

  1. JS: Object Object
  2. JS: Object.prototype
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth