- This topic is empty.
-
AuthorPosts
-
December 13, 2023 at 3:37 am #9334tyssenParticipant
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 thisconst 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?December 13, 2023 at 3:45 am #9335reihandioParticipantTo 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:
function transformFormData(formData) { const data = {}; for (let [key, value] of formData.entries()) { if (key.startsWith('other[')) { const nestedKey = key.substring(key.indexOf('[') + 1, key.indexOf(']')); if (!data['other']) { data['other'] = {}; } data['other'][nestedKey] = value; } else { data[key] = value; } } return data; }data; }
Replace your current data preparation process with this function:
const data = transformFormData(new FormData(this.form));
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.
-
AuthorPosts
- You must be logged in to reply to this topic.