Search code examples
javascriptstrict

Deleting an Object Entry with delete in Strict Mode


I have a vue project where I have to submit the form entries to api endpoint. Unfortunately any empty fields that are submitted throw an error on the server. So I came up with a .filter like method for the form object as follows:

Object.entries(formValues).forEach(([key, value]) => {
        if (value === "") {
          delete key;
        }
      });

The object is:

form: {
        searchTerm: "",
        mediaType: "",
        yearStart: "",
        yearEnd: ""
      }

I did not know the delete command was prevented on local variables in strict mode which is being applied by WebPack. Is there a way to delete the Object entry? Have not seen this scenario answered on different sites.


Solution

  • You should use the object explicitly in order to remove attributes/properties from an object:

    Object.entries(formValues).forEach([key, value] => {
      if (value === "") {
        delete formValues[key];
      }
    });