JavaScript: Create a deep clone of an object
JavaScript fundamental (ES6 Syntax): Exercise-71 with Solution
Write a JavaScript program to create a deep clone of an object.
- Use recursion.
- Check if the passed object is null and, if so, return null.
- Use Object.assign() and an empty object ({}) to create a shallow clone of the original.
- Use Object.keys() and Array.prototype.forEach() to determine which key-value pairs need to be deep cloned.
- If the object is an Array, set the clone's length to that of the original and use Array.from(clone) to create a clone.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const deepClone = obj => {
let clone = Object.assign({}, obj);
Object.keys(clone).forEach(
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
);
return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;
};
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = deepClone(a); // a !== b, a.obj !== b.obj
console.log(b)
Sample Output:
{"foo":"bar","obj":{"a":1,"b":2}}
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-71-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to count the occurrences of a value in an array.
Next: Write a JavaScript program to detect if the website is being opened in a mobile device or a desktop/laptop.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
JavaScript: Tips of the Day
Creates an object from the given key-value pairs
Example:
const tips_objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); console.log(tips_objectFromPairs([['x', 2], ['y', 4]]));
Output:
[object Object] { x: 2, y: 4 }
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework