layout: bpost title: "Append an array to formdata in JavaScript" image: "images/content/updating-angular-cli-projects.png" excerpt: "This code example will teach you how to append an array to formdata in JavaScript." categories: [javascript] permalink: /append-array-formdata-javascript/

tags: [javascript]

This code example will teach you how to append an array to formdata in JavaScript:

const formData = new FormData();
for (let key in form) {
    if(Array.isArray(form[key])){
        form[key].forEach(v => formData.append(key + '[]', v));
    }
    else {
        formData.append(key, form[key]) ;
    }
}

To appedn a an array to a FormData instance, it is necessary to loop over its key-value pairs and manually add keys and values to the newly created FormData object. For the purposes of this example, the forEach() JavaScript loop will be used.

We iterate over the form then we check if the current form element is an array using the isArray() method. If it is an array we iterate over its elements using the forEach() method wan we append each element to the FormData instance.