

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How would you deep copy an Object in Javascript?
A deep copy of an object duplicates every object it encounters within the object we want to copy. The copy and the original object will not share anything, so it will be a copy of the original.
The easiest way is to convert the object to JSON string and convert it back to a JS object. This way however doesn't allow method copying.
Example
let obj = { foo: 1, bar: { baz: 'test' } } let newObj = JSON.parse(JSON.stringify(obj)); obj.bar.baz = 20; console.log(obj); console.log(newObj);
Output
{ foo: 1, bar: { baz: 20 } } { foo: 1, bar: { baz: 'test' } }
The newObj here doesn't change with update to original obj, so deep copying was successful.
- Related Questions & Answers
- How do you do a deep copy of an object in .NET?
- Explain Deep cloning an object in JavaScript with an example.
- Deep Copy and Shallow Copy in Java
- Deep Search JSON Object JavaScript
- Copy - Shallow and deep copy operations in Python
- What is deep copy? Explain with an example in Java.
- Python Shallow and Deep Copy operations
- How to deep flatten an array in JavaScript?
- What is the most efficient way to deep clone an object in JavaScript?
- Deep Copy of Struct Member Arrays in C
- What is Shallow Copy and how it is different from Deep Copy in C#?
- What is the difference between shallow copy and deep copy in Java?
- How to create a copy of an object in PHP?
- Deep count of elements of an array using JavaScript
- How would you convert string to bytes in Python 3?
Advertisements