JS, how to append array in FormData?

10,619

You need to stringify your data first:

fd.append("key", JSON.stringify(["a","b","c"]));

And then when you want to retrieve the data parse it back into an array. This can be done manually using JSON.parse(), or, if you're using express, can be done for you by using the JSON/urlencoded body-parser middleware.


Explanation:

When you use .append(), the data passed as a second argument will be converted into a string. In the case of an array, the .toString() method gets called which joins the elements inside your array by a comma

a,b,c

This isn't good as this cannot be parsed back into the array easily, especially when you have complex arrays such as an array of objects or a multi-dimensional array.

However, as @Phil pointed out, you can manage this by using JSON.stringify on your input array. This way, you're providing a JSON string, which can easily be parsed back into data using JSON.parse()

"[\"a\",\"b\",\"c\"]" // <-- can be parsed into an array using JSON.parse()

See working example below:

var fd = new FormData();
fd.append("key", JSON.stringify(["a","b","c"]));

var str_arr = fd.get("key");
console.log(str_arr); // string format
console.log(JSON.parse(str_arr)); // array format
Share:
10,619
gdk
Author by

gdk

Updated on June 04, 2022

Comments

  • gdk
    gdk almost 2 years

    i hope append array in js FormData.

    like this,

    var fd = new FormData();
    fd.append("key", new Array(["a","b","c"]));
    console.log(fd.get("key"));
    

    the result is,

    a,b,c
    

    result type is 'String'...

    i want to parse "aa" array in java(JSONArray).

    please help me.

  • Phil
    Phil over 5 years
    Why not use JSON.stringify() on the value when appending it instead of attempting to build your own JSON formatter
  • Nick Parsons
    Nick Parsons over 5 years
    @Phil good point actually! I've updated my answer to use this instead. thanks
  • bubble-cord
    bubble-cord over 3 years
    Anyone new coming here for reference, fd.append("key", JSON.stringify(new Array(["a","b","c"]))); can be simply eased to fd.append("key", JSON.stringify(["a","b","c"]));. No need to add new Array to an existing array of items.
  • Nick Parsons
    Nick Parsons over 3 years
    @bubble-cord good point, I must’ve kept it from the OP’s question. I’ve updated it to remove the array constructor