Deep clone objects in JavaScript

Deep clone object methods in JavaScript:

1Loadash:

var obj = {yami: "code", code: ["yamicode", "yamitemplate", "yamitop10", {yamicode: "yamicode"}], yamicode: {yami: [1, 2, 3, 4], code: "yamicode"}};
var obj2 = _.clone(obj, true);

2Custom code:

var obj = {yami: "code", code: ["yamicode", "yamitemplate", "yamitop10", {yamicode: "yamicode"}], yamicode: {yami: [1, 2, 3, 4], code: "yamicode"}};
function clone(obj) {
  let copy = Array.isArray(obj) ? [] : {};
  	for (let prop in obj) {
    	let value = obj[prop];
    	if(value && typeof value === 'object') {
      		copy[prop] = clone(value);
  		} else {
      		copy[prop] = value;
  		}
 	}
    return copy;
}
var obj2 = clone(obj);

3jQuery:

var obj = {yami: "code", code: ["yamicode", "yamitemplate", "yamitop10", {yamicode: "yamicode"}], yamicode: {yami: [1, 2, 3, 4], code: "yamicode"}};
var obj2 = jQuery.extend(true, {}, obj);

4Angular:

var obj = {yami: "code", code: ["yamicode", "yamitemplate", "yamitop10", {yamicode: "yamicode"}], yamicode: {yami: [1, 2, 3, 4], code: "yamicode"}};
var obj2 = angular.copy(obj);

5JSON strigify:

var obj = {yami: "code", code: ["yamicode", "yamitemplate", "yamitop10", {yamicode: "yamicode"}], yamicode: {yami: [1, 2, 3, 4], code: "yamicode"}};
var obj2 = JSON.parse(JSON.stringify(obj));

Comapare deep clone object methods based on performance: performance test

deep clone object methods performance

The most efficient method is using loadash to avoid this common errors:

  • Converting circular structure to JSON
  • Maximum call stack size exceeded