obj2que-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:14:28 24 4
gpt4 key购买 nike

我无法申请 reduceObject 以查询字符串格式获取它。

我想要这个:

> 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(), safely

最佳答案

与其执行 reduce,更简洁的方法是 mapjoin

Object.keys(obj).map(function(x){
return x + '=' + obj[x];
}).join('&');
  • ma​​p 生成这样的数组:["a=1", "b=213123", "c=null", "d=false"]
  • join 将其转换为查询字符串:a=1&b=213123&c=null&d=false

关于使用 reduce 将 Javascript 对象转换为查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32831487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com