Search code examples
javascriptform-data

Deleting objects stored in formData based on attribute other than key


I am storing files into formData like such:

formData.append("images[]", file)
formData.append("images[]", file_2)
formData.append("images[]", file_3)

I know it's possible to delete the files using formData.delete(), but in this case, since all of the keys are the same, how do I specifically delete the object where the value is for example, file_2?


Solution

  • The function getAll() returns an array containing all values of a specific key.

    var values = formData.getAll("images[]");
    

    Then you can delete a specific value from the array and set the modified array as new value.

    var index = values.indexOf(file_2); //only necessary if you dont know the index
    values.splice(index, 1);
    formData.set("images[]", values);