Plain Javascript Equivalent of jQuery.param()
You can also do that with pure JavaScript, but you have to write more lines of code. Try this:
HTML code for testing:
<p id="test"></p>
JavaScript to be fired onload:
a = {
userid:1,
gender: "male",
}
url = Object.keys(a).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(a[k])
}).join('&')
document.getElementById("test").innerHTML=url
The output is this:
userid=1&gender=male
You can try this on JSFIDDLE.NET, it works, here's the link: http://jsfiddle.net/ert93wbp/
@Amaynut's answer is awesome. But I do some simplify:
const obj = {
userid: 1,
gender: 'male'
}
const params = Object.keys(obj).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k])).join('&')
or maybe modulize it using es6 module:
util.js
export default {
params (obj) {
return Object.keys(obj).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k])).join('&')
}
}
and use like this:
import util from './util'
const q = {
userid: 1,
gender: 'male'
}
const query = util.params(q)
console.log(query)
ES6 version that allows to convert nested objects and arrays just use like encodeURI(getUrlString({a: 1, b: [true, 12.3, "string"]}))
.
getUrlString (params, keys = [], isArray = false) {
const p = Object.keys(params).map(key => {
let val = params[key]
if ("[object Object]" === Object.prototype.toString.call(val) || Array.isArray(val)) {
if (Array.isArray(params)) {
keys.push("")
} else {
keys.push(key)
}
return getUrlString(val, keys, Array.isArray(val))
} else {
let tKey = key
if (keys.length > 0) {
const tKeys = isArray ? keys : [...keys, key]
tKey = tKeys.reduce((str, k) => { return "" === str ? k : `${str}[${k}]` }, "")
}
if (isArray) {
return `${ tKey }[]=${ val }`
} else {
return `${ tKey }=${ val }`
}
}
}).join('&')
keys.pop()
return p
}