Last active
March 17, 2020 20:54
-
-
Save ortense/71ef5517f302dd8968fb674034a6684a to your computer and use it in GitHub Desktop.
javascript deep clone without JSON.parse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cloneArray = array => array.map(deepClone) | |
const cloneObject = object => | |
Object.keys(object) | |
.reduce((clone, key) => ({ ...clone, [key]: deepClone(object[key])}), {}) | |
export const deepClone = value => | |
Array.isArray(value) | |
? cloneArray(value) | |
: value !== null && typeof value === 'object' | |
? cloneObject(value) | |
: value |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { deepClone } from './deep-clone.js' | |
const me = { | |
name: { | |
first: 'Marcus', | |
last: 'Ortense' | |
}, | |
cats: [ { neme: 'Minato', color: 'yellow' }, { name: 'Hiei', color: 'black' } ], | |
chapter: 'js' | |
} | |
console.log(deepClone(me)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#bonito