I have a form that has fields like name
email
other[a]
other[b]
which is submitted by AJAX. At the moment, the script that prepares the data before using Axios for posting does this
const data = Array.from(new FormData(this.form).entries()).reduce((memo, pair) => ({
...memo,
[pair[0]]: pair[1],
}), {});
which produces
{
"name":"X",
"email":"Y",
"other[a]":"A",
"other[b]":"B",
}
but it needs to be
{
"name":"X",
"email":"Y",
"other": {
"a": "A",
"b": "B"
}
}
What do I need to do so that the other
fields become a nested array?
2
Answers
To transform the other fields into a nested object, you can modify the data preparation process. You’ll need to split the field names and structure the object accordingly. Here’s a function you can use:
Replace your current data preparation process with this function:
This function iterates through the form data entries and checks if the key starts with ‘other’. If it does, it extracts the nested key (like ‘a’ or ‘b’) and structures the object accordingly. Otherwise, it stores the key-value pair directly in the main object.
Now that the syntax with the square brackets isn’t useful in JavaScript, you can skip the brackets and create your own syntax. Suggestions other than
other[a]
could be:other.a
,other/a
,other_a
etc.My suggestion would be a separator that does not conflict with identifiers in JavaScript. As an example, in forms names are useful. You can refer to the input element with the name "email" like this:
document.forms.form01.email
. In the case of square brackets in the name this way of referring to an element would be less elegant. This does not work:document.forms.form01.other[a]
, but this does:document.forms.form01['other[a]']
. With this in mind underscore_
would be a good choice:document.forms.form01.other_a
.With the following example you can create nested objects using the "underscore syntax":