Skip to content

Instantly share code, notes, and snippets.

@DoctorDerek
Last active May 1, 2022 20:49
Show Gist options
  • Save DoctorDerek/f8e8b5a88faa2253246bffbfb432f2a2 to your computer and use it in GitHub Desktop.
Save DoctorDerek/f8e8b5a88faa2253246bffbfb432f2a2 to your computer and use it in GitHub Desktop.
// Try this code sample at https://npm.runkit.com/lodash.clonedeep
const lodashClonedeep = require("lodash.clonedeep")
// Start with a deeply nested array object:
const array = [37, {a: "b"}, {b: {c: "d"}}]
// Make a deep copy with lodashClonedeep:
const copy = lodashClonedeep(array)
console.info(array) // [37, {a: "b"}, {b: {c: "d"}}]
copy[0] = -0 // Change a primitive value (not nested)
copy[1].a = "y" // Change a deeply nested value
copy[2].b.c = "z" // Change another deeply nested value
// Deeply nested objects were actually copied this time:
console.info(array) // [37, {a: "b"}, {b: {c: "d"}}]
// Note how the changes to copy did not affect array:
console.info(copy) // [-0, {a: "y"}, {b: {c: "z"}}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment