DEV Community

Discussion on: JavaScript Interviews: Create a deep copy of an object

Collapse
 
sprakashk profile image
Satyaprakash Kumawat

Object.prototype.toString.call(source[key]) === "[object Object]" can be used to identify if the value is an Object and rest can be directly put in the resulting object.

if the source input is as below:

let source = {
a: 10,
b: 20,
c: [1,2,3,4]
}

the output will be. here the c was n array and it got converted to object.

{
"a": 10,
"b": 20,
"c": {
"0": 1,
"1": 2,
"2": 3,
"3": 4
}
}

If we use Object.prototype.toString.call(source[key]) === "[object Object]" it will clone properly.