skip to Main Content

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


  1. 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:

    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.

    Login or Signup to reply.
  2. 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":

    let formdata = new FormData(document.forms.form01);
    
    let data = [...formdata].reduce((data, pair) => {
      let subobj = data;
      pair[0].split('_').forEach((key, i, arr) => {
        let value = (i + 1 < arr.length) ? {} : pair[1];
        if (!subobj[key]) subobj[key] = value;
        subobj = subobj[key];
      });
      return data;
    }, {});
    
    console.log(data);
    <form name="form01">
      <input name="name" value="X">
      <input name="email" value="Y">
      <input name="other_a" value="A">
      <input name="other_b" value="B">
      <input name="other_c_d" value="D">
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search