Search code examples
javascriptreactjsmultipartform-data

How to create an formdata that contains a running index in its field name?


I need to create an formdata that contains a running index in its name as well as its value. My previous approach (see beyond) fails due to a syntax error. But appart from that im not sure if it is gernally possible.

  for (var i = 0; i < files.length; i++) {
    formData.append('story_media'[i]'isTitlePicture', files[i].isTitlePicture)
    formData.append('story_files'[i]'files', files[i].file)
  }

The target is to achieve a formdata strucutre like this, as that is what my backend understands.

enter image description here

Im happy for any clarification.


Solution

  •   for (var i = 0; i < files.length; i++) {
        formData.append(`story_media[${i}]isTitlePicture`, files[i].isTitlePicture)
        formData.append(`story_files[${i}]files`, files[i].file)
      }