Method 1

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

The advantages and disadvantages

1, simple writing method

2, suitable for small amount of data in accordance with the JSON format data

3, large amount of data consumption memory

4, only suitable for json format data

Method 2

function clone(item) { if (! item) { return item; } // null, undefined values check var types = [ Number, String, Boolean ], result; // normalizing primitives if someone did new String('aaa'), or new Number('444'); types.forEach(function(type) { if (item instanceof type) { result = type( item ); }}); if (typeof result == "undefined") { if (Object.prototype.toString.call( item ) === "[object Array]") { result = []; item.forEach(function(child, index, array) { result[index] = clone( child ); }); } else if (typeof item == "object") { // testing that this is DOM if (item.nodeType && typeof item.cloneNode == "function") { result = item.cloneNode( true ); } else if (! item.prototype) { // check that this is a literal if (item instanceof Date) { result = new Date(item); } else { // it is an object literal result = {}; for (var i in item) { result[i] = clone( item[i] ); } } } else { // depending what you would like here, // just keep the reference, or create new object if (false && item.constructor) { // would not advice to do that, reason? Read below result = new item.constructor(); } else { result = item; } } } else { result = item; } } return result; }

Let’s do another way of writing ES6

function deepClone(obj, hash = new WeakMap()) { if (Object(obj) ! == obj) return obj; // primitives if (hash.has(obj)) return hash.get(obj); // cyclic reference const result = obj instanceof Set ? new Set(obj) // See note about this! : obj instanceof Map ? new Map(Array.from(obj, ([key, val]) => [key, deepClone(val, hash)])) : obj instanceof Date ? new Date(obj) : obj instanceof RegExp ? new RegExp(obj.source, obj.flags) // ... add here any specific treatment for other classes ... // and finally a catch-all: : obj.constructor ? new obj.constructor() : Object.create(null); hash.set(obj, result); return Object.assign(result, ... Object.keys(obj).map( key => ({ [key]: deepClone(obj[key], hash) }) )); }

The advantages and disadvantages

1, suitable for various data types of deep cloning

2, the code is large, suitable for encapsulation in the public class function

Methods 3

_.cloneDeep(object)

_.cloneDeepWith(object, (val) => {if(_.isElement(val)) return val.cloneNode(true)})

The advantages and disadvantages

1. The tool library is packaged and used, and the performance is better adjusted. 2

There are also methods for specific data types

Such as

Const arr1 = [1, 2, 3]; Const arr2 = Array. The from (arr1)
Array.prototype.concat() arrayObject.concat(arrayX,arrayX,...... ,arrayX)

Reference: [How to Deep clone in javascript] (https://stackoverflow.com/que…