Wrap array output in curly brackets and add relevant data label

487 Views Asked by At

I'm attempting to create a API connection and need to output html form data as a JSON array. But my current output doesn't match the API documentation.

I've managed to get to a point where I am outputting the form data into a JSON friendly format but trying to match the documentations format is causing me trouble. Here is a link to the documentation: https://developer.infusionsoft.com/docs/rest/#!/Contact/createContactUsingPOST

const isEmail = element => element.type === 'email';

const formToJSON = elements => [].reduce.call(elements, (data, element) => {

  if (isValidElement(element) && isValidValue(element)) {

    if (isEmail(element)) {
      data[element.name] = (data[element.name] || []).concat(element.value);
    } else {
      data[element.name] = element.value;
    }
  }

  return data;
}, {});

const handleFormSubmit = event => {

  event.preventDefault();
  const data = formToJSON(form.elements);
  dataContainer.textContent = JSON.stringify(data, null, "  ");

};

const form = document.getElementsByClassName('contact-form')[0];
form.addEventListener('submit', handleFormSubmit);
<form class="contact-form">
  <input type="email" placeholder="Email" name="email_addresses" required="required">
  <input type="submit" placeholder="submit" value="submit" name="submit">
</form>

Current output if it's an email field

  "email_addresses": [
    "[email protected]"
  ],

What output should look like.

"email_addresses": [
    {
      "email": "string",
      "field": "EMAIL1"
    }
  ],
1

There are 1 best solutions below

0
Josh Ratcliffe On BEST ANSWER

@Tom posted an answer in the comments that I tried.

data[element.name] = []; var item = {"email": undefined,"field": "EMAIL1"};
item.email = (data[element.name] || []).concat(element.value);
data[element.name].push(item);

Results in the following output

"email_addresses": [
    {
      "email": [
        "[email protected]"
      ],
      "field": "EMAIL1"
    }
  ],

Removing (data[element.name] || []).concat results in the expected output of:

"email_addresses": [
    {
      "email": "[email protected]",
      "field": "EMAIL1"
    }
  ],