javascript deep copy code example

Example 1: deep clone array in javascript

const numbers = [1, [2], [3, [4]], 5];

// Using JavaScript
JSON.parse(JSON.stringify(numbers));

// Using Lodash
_.cloneDeep(numbers);

Example 2: deep clone object javascript

JSON.parse(JSON.stringify(object))

Example 3: clone javascript object

let clone = Object.assign({}, objToClone);

Example 4: javascript deep clone

var cloned = JSON.parse(JSON.stringify(objectToClone));

Example 5: how to make a deep copy in javascript

JSON.parse(JSON.stringify(o))

Example 6: deep copy javascript

function copy(arr1, arr2) {
	for (var i =0; i< arr1.length; i++) {
    	arr2[i] = arr1[i];
    }
}
copy(arr1, arr2)