JavaScript achieve deep copy
Copy when it comes to:
1, a cyclic structure
2, or the object is determined Array Array Object
Function to achieve
/ * * * Get the first element of the array satisfies the condition in * @param {Array} list will be screened array * @param {Function} for which filtering function f * / function Find (List, f) { return List .filter (F) [0 ] } / * * * deep copy of the object, taking into account the case where the circular reference * all cached copies of its nested objects and * if circular reference is detected, returns a copy to prevent an infinite loop * @param {object} obj of the object to be copied * @param {Array} cache circular reference used to determine whether, and stores a copy of the object the object * / function the deepCopy (obj, Cache = []) { // is empty or not Object obj returns the original IF (obj === null || typeof obj! == 'Object' ) { return obj } // if the cyclic structure, Copy before the object is returned, instead of a reference const HIT = Find (Cache, C => c.original === obj) IF (HIT) { return hit.copy } const Copy = the Array. isArray (obj)? []: {} // will copy into the cache // we might refer to the recursive copy cache.push ({ Original: obj, copy }) Object.keys (obj) .forEach (Key = > { Copy [Key] = the deepCopy (obj [Key], Cache) }) return Copy }
application
1, non-nested examples:
const original = { a: 1, b: 'string', c: true, d: null, e: undefined } const copy = deepCopy(original) console.log('copy === original :', copy === original) // copy === original : false console.log('copy :', JSON.stringify(copy, null, 2)) // copy : { // "a": 1, // "b": "string", // "c": true, // "d": null // }
2, the nested example:
const original = { a: { b: 1, c: [ 2, 3, { d: 4 } ] } } const copy = deepCopy(original) console.log('copy === original :', copy === original) // copy === original : false console.log('copy :', JSON.stringify(copy, null, 2)) // copy : { // "a": { // "b": 1, // "c": [ // 2, // 3, // { // "d": 4 // } // ] // } // }
3, circular references
Original = const { A: . 1 } original.circularExample = Original const Copy = the deepCopy (Original) the console.log ( 'Copy Original ===:', === Copy Original) // Copy Original ===: to false Console. log ( 'Copy:' , Copy) // herein circular references can not be used to convert JSON.stringify, being given // Copy: {A:. 1, circularExample: [circular]}