I have a javascript object that I need to flatten into a string so that I can pass as querystring, how would I do that? i.e:
{ cost: 12345, insertBy: 'testUser' }
would become cost=12345&insertBy=testUser
I can't use jQuery AJAX call for this call, I know we can use that and pass the object in as data
but not in this case. Using jQuery to flatten to object would be okay though.
Thank you.
Here is another non-jQuery version that utilizes lodash or underscore if you're already using one of those libraries:
you can use this
try on JSFiddle on this link https://jsfiddle.net/yussan/kwmnkca6/
You want
jQuery.param
:Note that this is the function used internally by jQuery to serialize objects passed as the
data
argument.Here's a non-jQuery version:
My ES6 version (pure Javascript, no jQuery):
This is an old question, but at the top of Google searches, so I'm adding this for completeness.
If 1) you don't want to user jQuery, but 2) you want to covert a nested object to a query string, then (building off of Tim Down and Guy's answers), use this:
Use like:
Which outputs: