I’m having trouble to apply a reduce to an Object
to get it in a querystring format.
I want this:
> var obj = {a: 1, b: "213123", c: null, d:false} > obj2querystring(obj); a=1&b=213123&c=null&d=false
So far, the close I have got is this:
Object.keys(obj).reduce(function(prev, curr){ return prev + '&' + curr + '=' + obj[curr]; }, '');
which gives me:
&a=1&b=213123&c=null&d=false
Is there an easier way to achieve this without have to prepend the initialValue and remove the &
later?
EDIT: This question is old and today we can just use new URLSearchParams(object).toString()
, safely
Advertisement
Answer
Instead of doing a reduce
, a cleaner way would be map
and join
.
Object.keys(obj).map(function(x){ return x + '=' + obj[x]; }).join('&');
- map makes and array like this:
["a=1", "b=213123", "c=null", "d=false"]
- join turns it into a query string:
a=1&b=213123&c=null&d=false