title: Encode object literal as URL query string in Javascript
body: <p>I am trying to get rid of the jQuery dependency in a project. One thing that project does is posting data to a server like so:</p>
  
  <pre><code>var data = {"apple": [{"kiwi": "orange"}, {"banana": "lemon"}], "pear": "passion fruit"};
  $.post( url, data);
  </code></pre>
  
  <p>Thanks to <a href="http://youmightnotneedjquery.com/#post" rel="nofollow noreferrer">You might not need jQuery</a>, I know how to rewrite <code>$.post</code> in pure Javascript using <code>XMLHttpRequest</code>:</p>
  
  <pre><code>var request = new XMLHttpRequest();
  request.open( 'POST', url, true);
  request.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  request.send( data);
  </code></pre>
  
  <p>Unfortunately, this description seems to assume that the <code>data</code> object is already a URL-encoded query string, which is clearly not the case in the above example. It turns out jQuery does more than that: With the given <code>data</code> object, the above <code>$.post</code> call would first convert it to a query string, which would look like so:</p>
  
  <pre><code>apple%5B0%5D%5Bkiwi%5D=orange&amp;apple%5B1%5D%5Bbanana%5D=lemon&amp;pear=passion+fruit
  </code></pre>
  
  <p>The code snippet using <code>XMLHttpRequest</code> does not do so, and, thus, the server will throw errors at me.</p>
  
  <p>jQuery also has a wonderful method call <a href="http://api.jquery.com/jquery.param/" rel="nofollow noreferrer"><code>$.param</code></a> which does exactly this conversion. The above code snippet using <code>XMLHttpRequest</code> will work marvelously if in the last line I do</p>
  
  <pre><code>request.send( $.param(data));
  </code></pre>
  
  <p>But then, I did not get rid of the jQuery dependency. So I'm looking for a pure Javascript equivalent of <code>$.param</code>. Does anyone have something like that?</p>
  
  <p><strong>Note:</strong> The question <a href="https://stackoverflow.com/questions/25224887/plain-javascript-equivalent-of-jquery-param">Plain Javascript Equivalent of jQuery.param()</a> asks a similar question, but the accepted answer only works in very simple cases. Applying the function given in that answer to my above <code>data</code> object yields:</p>
  
  <pre><code>apple=%5Bobject%20Object%5D%2C%5Bobject%20Object%5D&amp;pear=passion%20fruit
  </code></pre>
  
  <p>...which is obviously different from the result of <code>$.param(data)</code> given above, and loses information since it doesn't work recursively.</p>