Cloning objects and arrays in JavaScript

30.04.19

For cloning objects in JS there is no specially provided method. You can copy an object in different ways. Since objects are passed by reference, we cannot clone simply by assigning a value to a variable.

Objects

With Spread

let originalObject = {a: 1};
let clone = {...originalObject};

With Object.assign()

let originalObject = {a: 1};
let clone = Object.assign({}, originalObject);

With a loop

let clone = {};
 
for (let key in originalObject) {
  clone[key] = originalObject[key];
}

With jQuery

let clone = jQuery.extend(true, {}, originalObject);

With JSON object

let clone = JSON.parse(JSON.stringify(originalObject));

Arrays

With Spread

let clone = [...originalArray];

With Slice

let clone = originalArray.slice();
blog comments powered by Disqus