Skip to content

Instantly share code, notes, and snippets.

@wilsoncook
Last active April 12, 2018 12:07
Show Gist options
  • Save wilsoncook/ed4986fe283fd5d5be7291063dabf355 to your computer and use it in GitHub Desktop.
Save wilsoncook/ed4986fe283fd5d5be7291063dabf355 to your computer and use it in GitHub Desktop.
Deep clone for javascript
/**
* 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