1

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?

Logan L.
  • 85
  • 7
  • 1
    object are shared by reference, not value, hence deleting one property will affect all objects that sharing the same reference. You might want to create another object instead if you wish to keep as two different copies – Isaac Jul 02 '18 at 00:54
  • 1
    >I'm not seeing that might be affecting the original object ---------------In Javascript objects and arrays follows pass by reference – NullPointer Jul 02 '18 at 01:11
  • 1
    Possible duplicate of [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – jhpratt Jul 02 '18 at 01:15

1 Answers1

1

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);
Logan L.
  • 85
  • 7
  • Note that this _only_ works for objects that can be stringified and parsed. Functions, classes, etc. cannot be handled this way. – jhpratt Jul 02 '18 at 01:14