Update deepClone.md
This commit is contained in:
@ -4,11 +4,13 @@ tags: object,recursion,intermediate
|
|||||||
---
|
---
|
||||||
|
|
||||||
Creates a deep clone of an object.
|
Creates a deep clone of an object.
|
||||||
|
Clones primitives, arrays and objects, excluding class instances.
|
||||||
|
|
||||||
Use recursion.
|
Use recursion.
|
||||||
Check if the passed object is `null` and, if so, return `null`.
|
Check if the passed object is `null` and, if so, return `null`.
|
||||||
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
|
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
|
||||||
Use `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.
|
Use `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.
|
||||||
|
If the object is an `Array`, set the `clone`'s `length` to that of the original and use `Array.from(clone)` to create a clone.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const deepClone = obj => {
|
const deepClone = obj => {
|
||||||
@ -17,11 +19,11 @@ const deepClone = obj => {
|
|||||||
Object.keys(clone).forEach(
|
Object.keys(clone).forEach(
|
||||||
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
|
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
|
||||||
);
|
);
|
||||||
return Array.isArray(obj) && obj.length
|
if (Array.isArray(obj)) {
|
||||||
? (clone.length = obj.length) && Array.from(clone)
|
clone.length = obj.length;
|
||||||
: Array.isArray(obj)
|
return Array.from(clone);
|
||||||
? Array.from(obj)
|
}
|
||||||
: clone;
|
return clone;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user