Files
30-seconds-of-code/snippets/deepClone.md
Robert Mennell 3d1da367b9 Update deepClone.md
We missed that the clone length wasn't there. This fixes the issue
2018-05-13 23:07:44 -07:00

23 lines
659 B
Markdown

### 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 Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;
};
```
```js
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a); // a !== b, a.obj !== b.obj
```