Add deepClone.md
This commit is contained in:
25
snippets/deepClone.md
Normal file
25
snippets/deepClone.md
Normal file
@ -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
|
||||||
|
```
|
||||||
@ -27,6 +27,7 @@ createEventHub:browser,event,advanced
|
|||||||
currentURL:browser,url
|
currentURL:browser,url
|
||||||
curry:function,recursion
|
curry:function,recursion
|
||||||
decapitalize:string,array
|
decapitalize:string,array
|
||||||
|
deepClone:object,recursion
|
||||||
deepFlatten:array,recursion
|
deepFlatten:array,recursion
|
||||||
defaults:object
|
defaults:object
|
||||||
defer:function
|
defer:function
|
||||||
@ -125,7 +126,7 @@ mapObject:array,object
|
|||||||
mapValues:object,function
|
mapValues:object,function
|
||||||
mask:string,utility,regexp
|
mask:string,utility,regexp
|
||||||
matches:object,type
|
matches:object,type
|
||||||
matchesWith:object,type,function
|
matchesWith:object,type,function
|
||||||
maxBy:math,array,function
|
maxBy:math,array,function
|
||||||
maxN:array,math
|
maxN:array,math
|
||||||
median:math,array
|
median:math,array
|
||||||
|
|||||||
Reference in New Issue
Block a user