[Special Summer Sale] 40% OFF All Magento 2 Themes

Cart

Convert form data into multi-dimensional array

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #9334
    tyssen
    Participant

    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?

    #9335
    reihandio
    Participant

    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.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.