Reputation: 85
I'm using a javascript proxy and in the set trap I want to to send data up to the server, but I don't want to send extra data that isn't needed so I try to delete the field in the object I'm sending up as show below.
let handler = function(data){
const SAVE_DELAY = 850;
return {
set:function(target, key, value){
let sendData = Object.assign({},data);
sendData[key] = Object.assign({}, value);
function updateTarget() {
if(!target.__isupdating){
if(target.__updateTimeout){
clearTimeout((target.__updateTimeout));
}
target.__updateTimeout = setTimeout(() => {
target.__isupdating = true;
delete target.__updateTimeout;
for (var i in sendData.field) {
if (sendData.field[i].field_to_delete) {
delete sendData.field[i].field_to_delete;
}
}
ajaxCall("/api_endpoint",
sendData,
function (response) {
target.__isupdating = false;
if(response.data){
// Update was success
}
},
function(error){
console.log("Error updating! ",error);
})
},SAVE_DELAY);
}
}
updateTarget();
return true;
}
};
}
After doing this delete I lose the field on the object it was cloned from ( value ) and I still need that field afterwards. Is there something I'm not seeing that might be affecting the original object in an unintended way?
Upvotes: 1
Views: 53
Reputation: 85
Okay thanks to Isaac, I looked up deep copying vs. shallow copying and was able to find the correct code to use which is
sendData[key] = JSON.parse(JSON.stringify(value));
as opposed to:
sendData[key] = Object.assign({}, value);
Upvotes: 1