I need a clone function for JavaScript literal objects, which doesn't even needs to clone recursively for now. The function needs to be pure JavaScript no libraries could be used. I've done some research and as some of the most simplified answers to this question suggests, all I need in this case is "for in" loop with hasOwnProperty check. The problem is that the supposedly copied object is behaving as if I've copied the references to the original properties in the new object. That is not my goal. The clone function in a way that any change of the source object does not affect the destination object and vice versa. Here is the code:
...
function clone(from,to){
for (var key in from){
if(from.hasOwnProperty(key)){
to[key]=from[key];
}
}
return to;
}
...
var newComponent = clone(component,{});
var defaultComponentDrawParams = clone(component.drawParams,{});
if(params.type==="button"){
console.info('new component');
component.drawParams.subType="chinga chunga";
console.info(defaultComponentDrawParams.subType);
console.info(newComponent.drawParams.subType);
}
And the console displays:
new component
saveFile
chinga chunga
If I've understood correctly both outputs after "new component" should be "undefined" because my goal is when changing component.drawParams to not change newComponent.drawParams. Please tell me what am I missing.