Last active
April 12, 2018 12:07
-
-
Save wilsoncook/ed4986fe283fd5d5be7291063dabf355 to your computer and use it in GitHub Desktop.
Deep clone for javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple clone JSON-like object (No circular reference, No class inherit, Plain object) | |
* [NOTE] Not tested on all cases | |
* @param obj object to be clone | |
* @param excludeFields exclude fields that will ignored copying | |
*/ | |
export function deepClone<T>(obj: any, excludeFields?: string[]) { | |
if (obj === null || typeof obj !== 'object') { return obj; } | |
if (Object.prototype.toString.call(obj) === '[object Array]') { | |
return obj.map((element) => deepClone(element, excludeFields)); | |
} | |
const newObj = {}; | |
for (const key in obj) { | |
if (Object.prototype.hasOwnProperty.call(obj, key)) { | |
if (!excludeFields || excludeFields.indexOf(key) === -1) { | |
newObj[key] = deepClone(obj[key], excludeFields); | |
} | |
} | |
} | |
return newObj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment