title: Use HTML input 'name' attribute to yield an Object
body: <p>In <em>ExpressJS</em> using <em>body-parser</em>, there exists the functionality to parse as a JavaScript object (or JSON, I'm not entirely sure) a set of input elements which have the same name attribute with defined keys.</p>
  
  <p><strong>HTML (e.g.)</strong>:</p>
  
  <pre><code>&lt;input type="text" class="name" name="name[foo]" placeholder="input1"/&gt;
  &lt;input type="text" class="name" name="name[bar]" placeholder="input2"/&gt;
  </code></pre>
  
  <p><strong>JavaScript (e.g.)</strong>:</p>
  
  <pre><code>var obj = req.body.name;
  </code></pre>
  
  <p>The object <code>obj</code> is understood by JavaScript to be <code>{ "foo" : input1, "bar" : input2 }</code></p>
  
  <p>I am trying to get similar functionality using standard jQuery to handle several related form inputs.  What I have tried so far&mdash;to no avail&mdash;is the following:</p>
  
  <p><code>$(".name")</code> yields an Object containing the literal HTML (not helpful for grabbing the key-value pairs).</p>
  
  <p><code>$(".name").map(function () {return $(this).val();}).get();</code> yields an <em>array</em> of values, but no keys.</p>
  
  <p><code>$("input[name='name']")</code> and <code>$("input[name='name[]']")</code> yield nothing.</p>
  
  <p>I have also tried the following to convert the inputs to an array, but it still does not serve the purpose of pulling the information from the form as a JavaScript object/JSON:</p>
  
  <pre><code>$.fn.inputsToArray = function () {
    var values= [];
    $.each(this, function (i, field) {
      values.push(field.value);
    });
    return values;
  };
  </code></pre>
  
  <p>Is there a way to accomplish what I am trying to do without <em>NodeJS</em> / <em>body-parser</em>?</p>
  
  <hr>
  
  <p><strong>Solution:</strong></p>
  
  <p>Thanks to <a href="https://stackoverflow.com/users/3880585/gaetanom">gaetanoM</a>'s excellent solution (accepted below), I was able to create a generic jQuery function that can be called on any jQuery object (obviously, it'll only work properly if the element is in the <code>&lt;input ... name="example[key]" ... /&gt;</code> format, but I digress).</p>
  
  <p>The function is called thusly:</p>
  
  <pre><code>var output = $(":input[name^=example]").inputsToObject();
  </code></pre>
  
  <p>The function is defined as the following:</p>
  
  <pre><code>$.fn.inputsToObject = function () {
    var values = {};
    values = $(this).get().reduce(function (acc, ele) {
      var key = ele.name.match(/\[(.*)\]$/)[1];
      acc[key] = $(ele).val();
      return acc;
    }, {})
    return values;
  }
  </code></pre>