diff --git a/snippets/deepClone.md b/snippets/deepClone.md new file mode 100644 index 000000000..360505318 --- /dev/null +++ b/snippets/deepClone.md @@ -0,0 +1,25 @@ +### deepClone + +Creates a deep clone of an object. + +Use recursion. +Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original. +Use `Object.keys()` and `Array.forEach()` to determine which key-value pairs need to be deep cloned. + +```js +const deepClone = obj => { + let clone = Object.assign({}, obj); + Object.keys(clone).forEach( + key => + (clone[key] = typeof obj[key] === 'object' + ? deepClone(obj[key]) + : obj[key]) + ); + return clone; +}; +``` + +```js +const a = { foo: 'bar', obj: { a: 1, b: 2 } }; +const b = deepClone(a); // a !== b, a.obj !== b.obj +``` diff --git a/tag_database b/tag_database index ac660d49a..a929e397c 100644 --- a/tag_database +++ b/tag_database @@ -27,6 +27,7 @@ createEventHub:browser,event,advanced currentURL:browser,url curry:function,recursion decapitalize:string,array +deepClone:object,recursion deepFlatten:array,recursion defaults:object defer:function @@ -125,7 +126,7 @@ mapObject:array,object mapValues:object,function mask:string,utility,regexp matches:object,type -matchesWith:object,type,function +matchesWith:object,type,function maxBy:math,array,function maxN:array,math median:math,array