0

Error While creating Function | JS

I have created function for cloning object into another variable. Everything is fine but when I iterate over cloned object variable, it only shows key not properties. Please tell me why this is happening? Any answer would be appreciated! https://code.sololearn.com/W3DVN583MU6C/?ref=app (View code in landscape mode for convenience )

2nd Nov 2020, 2:32 PM
Himanshu Rai
Himanshu Rai - avatar
4 odpowiedzi
+ 4
srcObj.key is nothing in the original object since it is treated as srcObj."name", it is because key is string here when you loop over the object,you can use typeof to check the key type , Instead you should use srcObj[key] =>srcObj["name"] which works fine
2nd Nov 2020, 2:48 PM
Abhay
Abhay - avatar
+ 2
Change the logic to the following, if (typeof key === "object") { cloneObj(targetObj,key) } It calls function again with target object and key being the object
2nd Nov 2020, 3:21 PM
Abhay
Abhay - avatar
+ 1
Abhay yes, you said write, here key is variable and dot notation takes it as string. Thanks For solving!
2nd Nov 2020, 2:57 PM
Himanshu Rai
Himanshu Rai - avatar
0
Well how to create a function that can clone more nested object. Like here I have created function to clone 1 level nested object so how to create function that can clone object with unlimited nested levels?
2nd Nov 2020, 3:05 PM
Himanshu Rai
Himanshu Rai - avatar