使用reduce将Javascript对象转换为查询字符串

Javascript Object to querystring using reduce

本文关键字:查询 字符串 转换 对象 reduce Javascript 使用      更新时间:2023-09-26

我遇到了麻烦,以减少到一个Object得到它在查询字符串格式。

我想要这个:

> var obj = {a: 1, b: "213123", c: null, d:false}
> obj2querystring(obj);
a=1&b=213123&c=null&d=false

到目前为止,我得到的最接近的是:

Object.keys(obj).reduce(function(prev, curr){
    return prev + '&' + curr + '=' + obj[curr];
}, '');

得到:

&a=1&b=213123&c=null&d=false

是否有更简单的方法来实现这一点,而不必添加initialValue并稍后删除& ?


编辑:这个问题是老问题了,今天我们可以安全地使用new URLSearchParams(object).toString()

不做reduce,更干净的方法是mapjoin

Object.keys(obj).map(function(x){
    return x + '=' + obj[x];
}).join('&');
  • map make and array如下:["a=1", "b=213123", "c=null", "d=false"]
  • join将其转换为查询字符串:a=1&b=213123&c=null&d=false

您可以使用mapjoin:

return Object.keys(obj).map(function(i) {
  return i + '=' + obj[i];
}).join('&');

在queryString的两边使用encodeURIComponent是很重要的:

return Object.keys(obj).map(function(i) {
  return encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
}).join('&');

如果您需要随时返回queryString:

location.search.slice(1).split('&').map(function(i) {
  var arr = i.split('=');
  var a = {};
  a[decodeURIComponent(arr[0])] = arr[1] ? decodeURIComponent(arr[1]) : void 0;
  return a;
}).reduce(function(a, b) {
  var key = Object.keys(b)[0];
  a[key] = b[key];
  return a;
});