The most efficient way to deep clone an object in JavaScript
Hi everyone! I'm new to JavaScript and ran into a problem when copying objects. I need to create an independent copy of an object so that changes to the copy don't affect the original.
Here's an example of code that doesn't work for me:
```javascript
const original = {
name: 'Anna',
age: 25,
address: {
city: 'Moscow',
street: 'Lenina'
},
hobbies: ['reading', 'sport']
};
const copy = original;
copy.name = 'Maria';
copy.address.city = 'SPb';
console.log(original.name); // 'Maria' — changed!
console.log(original.address.city); // 'SPb' — also changed!
```
I tried using `Object.assign()` and the spread operator:
```javascript
const copy2 = Object.assign({}, original);
const copy3 = {...original};
copy2.address.city = 'Kazan';
console.
No answers yet.
Log in to leave an answer