@spa-tools/utilities
deepClone()
The ES6 spread ...
operator was a huge game changer when it was released. And
for simple object/array copies, it's the go-to choice. But as powerful as it is,
it falls short for copying objects or arrays that hold
nested reference values.
This is where the deepClone<T>()
function comes in. It's a simple utility that allows you to
deeply clone an object or array, including nested reference values.
The generic T
type is used to define the type of data being cloned.
Usage
import { deepClone } from '@spa-tools/utilities';
const original = {
address: {
city: 'New York',
country: 'USA'
},
hobbies: ['reading', 'coding'],
name: 'John'
children: [
{ name: 'Alice',
attributes: { age: 10, eyeColor: 'blue', hairColor: 'brown' }
},
{ name: 'Sam',
attributes: { age: 8, eyeColor: 'green', hairColor: 'blonde'}
},
]
};
const cloned = deepClone(original);
console.log(cloned);
console.log(cloned === original);
// --> false
console.log(cloned.children[0] === original.children[0]);
// --> false
console.log(cloned.children[0].attributes === original.children[0].attributes);
// --> false
Arguments
Name | Type | Description |
---|---|---|
value | T | The data to clone |
Returns
Returns T
.