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: \'testUse
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("&");
}
Here is another non-jQuery version that utilizes lodash or underscore if you're already using one of those libraries:
var toQueryString = function(obj) {
return _.map(obj,function(v,k){
return encodeURIComponent(k) + '=' + encodeURIComponent(v);
}).join('&');
};
^ I wrote that 5 years ago. An updated and more succinct version of this would now (Oct 2019) be:
var input = { cost: 12345, insertBy: 'testUser' };
Object.entries(input)
.map(([k,v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
// cost=12345&insertBy=testUser
Check that the runtime that you're targeting supports Object.entries() or that you're using a transpiler like Babel or TypeScript if it doesn't.
Another version:
function toQueryString(obj) {
return Object.keys(obj).map(k => {
return encodeURIComponent(k) + "=" + encodeURIComponent(obj[k])
})
.join("&");
}
you can use this
function serialize(obj)
{
let str = []
for(var p in obj)
{
if(obj.hasOwnProperty(p)) str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
}
return str.join('&')
}
try on JSFiddle on this link https://jsfiddle.net/yussan/kwmnkca6/
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.
Using Lodash library it can be done as:
let data = {}
_.map(data, (value, key) => `${key}=${value}`)
.join("&");
Note that this library has been imported as:
window._ = require('lodash');