Skip to content

Instantly share code, notes, and snippets.

@ortense
Last active March 17, 2020 20:54
Show Gist options
  • Save ortense/71ef5517f302dd8968fb674034a6684a to your computer and use it in GitHub Desktop.
Save ortense/71ef5517f302dd8968fb674034a6684a to your computer and use it in GitHub Desktop.
javascript deep clone without JSON.parse
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
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))
@jlcarruda
Copy link

#bonito

@ortense
Copy link
Author

ortense commented Mar 17, 2020

#bonito

🖤

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment