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.

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) {
  if(originalObject.hasOwnProperty(key)){
    clone[key] = originalObject[key];
  }
}

With jQuery

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

With lodash

let clone = _.clone(value);

let cloneDeep = _.cloneDeep(value);

With JSON object

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

Arrays

With Spread

let clone = [...originalArray];

With Slice

let clone = originalArray.slice();
Lodash can also be used for array cloning

Comments

Popular posts from this blog

JavaScript Inheritance and Classes

Typical gulpfile.js

Swipe events on touch devices