Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 350
Takehiro Mouri Avatar asked Sep 06 '25 03:09

Takehiro Mouri


1 Answers

Not sure if this is the optimal way. But you can get all values using getAll. Then filter and append once again. Demo.

const form = new FormData
form.append('names[]', 'Chris')
form.append('names[]', 'Bob')
form.append('names[]', 'John')

console.log(Array.from(form.entries()))

const names = form.getAll('names[]')

form.delete('names[]')

names
    .filter(name => name !== 'Bob')
    .forEach(name => form.append('names[]', name))

console.log(Array.from(form.entries()))
like image 198
Yury Tarabanko Avatar answered Sep 07 '25 21:09

Yury Tarabanko