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.
We make a function called flatten object which takes input of an object and returns an object. Loop through the object and check the type of the current property: If it is of type Object and it is not an Array , recursively call the function again. Otherwise, store the value in the result.
A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.
Methods—setting functions as properties of objects. In JavaScript, you can use functions as values, just like numbers, strings, and objects. That means you can pass them as arguments, return them from other functions, and set them as properties of objects.
You want jQuery.param
:
var str = $.param({ cost: 12345, insertBy: 'testUser' }); // "cost=12345&insertBy=testUser"
Note that this is the function used internally by jQuery to serialize objects passed as the data
argument.
Here's a non-jQuery version:
function toQueryString(obj) { var parts = []; for (var i in obj) { if (obj.hasOwnProperty(i)) { parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i])); } } return parts.join("&"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With