I’m having trouble to apply a reduce to an Object
to get it in a querystring format.
I want this:
JavaScript
x
4
1
> var obj = {a: 1, b: "213123", c: null, d:false}
2
> obj2querystring(obj);
3
a=1&b=213123&c=null&d=false
4
So far, the close I have got is this:
JavaScript
1
4
1
Object.keys(obj).reduce(function(prev, curr){
2
return prev + '&' + curr + '=' + obj[curr];
3
}, '');
4
which gives me:
JavaScript
1
2
1
&a=1&b=213123&c=null&d=false
2
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
.
JavaScript
1
4
1
Object.keys(obj).map(function(x){
2
return x + '=' + obj[x];
3
}).join('&');
4
- 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