JavaScript: 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 JavaScript: 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.).

var oldArray = [3,4,5];

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

〔►see JavaScript: 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

var mm = [8];

var aa = [3,mm];

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

mm[0] = 4;

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

Array Topic

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

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype

Object and Inheritance Topic

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

  1. JavaScript: Object Object
  2. JavaScript: Object.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.