Cloning objects and arrays in JavaScript


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.


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));


With Spread

let clone = [...originalArray];

With Slice

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