Snippet - Array Deep Copy In One Line?

5 years ago

Hack: The easiest way to create a copy of any object without mutating it, is without any fancy library and only a simple one-liner. ;) It's easy to forget some of the forbidden fruit in JavaScript and it becomes immediately obvious once you see it.

Important: While tempting, you should NEVER EVER use this code as it can potentially kill performance. When writing pure function, always use more surgical approaches like destructuring or Object.assign.

Code

const deepCopy = obj => JSON.parse(JSON.stringify(obj))

Consuming the Code

let person = {
  id: 1,
  name: 'Joe',
  pets: ['cat', 'dog']
}

// Create copy and change
let newPerson = deepCopy(person)
newPerson.name = 'Joey'
newPerson.pets.push('fish')

// Print person and newPerson
console.log(person)
console.log(newPerson)

Results

// person (it has not been altered)
{
    "id": 1,
    "name": "Joe",
    "pets": [
        "cat",
        "dog"
    ]
}

// newPerson
{
    "id": 1,
    "name": "Joey",
    "pets": [
        "cat",
        "dog",
        "fish"
    ]
}

Source Code
Discuss on Twitter