是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?

没有jQuery,没有其他框架-只有纯JavaScript:)


当前回答

以下是已接受答案的CoffeeScript版本。

serialize = (obj, prefix) ->
  str = []
  for p, v of obj
    k = if prefix then prefix + "[" + p + "]" else p
    if typeof v == "object"
      str.push(serialize(v, k))
    else
      str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v))

  str.join("&")

其他回答

我的实现编码一个对象作为一个查询字符串,使用减少:

export const encodeAsQueryString = (params) => (
  Object.keys(params).reduce((acc, key)=>(
    params.hasOwnProperty(key) ? (
      [...acc, encodeURIComponent(key) + '=' + encodeURIComponent(params[key])]
    ) : acc
  ), []).join('&')
);

这个函数跳过null/undefined值

export function urlEncodeQueryParams(data) {
    const params = Object.keys(data).map(key => data[key] ? `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}` : '');
    return params.filter(value => !!value).join('&');
}

是这样的:

Serialize =函数(obj) { Var STR = []; For (var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]))); } 返回str.join(“&”); } console.log(序列化({ Foo:“你好”, 栏:“100%” })); / / foo =你好% 20 there&bar 25 = 100%

它还转换递归对象(使用PHP“数组”符号表示查询字符串):

serialize = function(obj, prefix) { var str = [], p; for (p in obj) { if (obj.hasOwnProperty(p)) { var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push((v !== null && typeof v === "object") ? serialize(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v)); } } return str.join("&"); } console.log(serialize({ foo: "hi there", bar: { blah: 123, quux: [1, 2, 3] } })); // foo=hi%20there&bar%5Bblah%5D=123&bar%5Bquux%5D%5B0%5D=1&bar%5Bquux%5D%5B1%5D=2&bar%5Bquux%5D%5B2%5D=3

好吧,似乎每个人都把他的俏皮话写在这里,所以我的是:

const encoded = Object.entries(obj).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
 let data = {
    id:1,
    name:'Newuser'
    };
const getqueryParam = data => {
  let datasize = Object.keys(data).length;
  let initial = '?';

  Object.keys(data).map(function (key, index) {
    initial = initial.concat(`${key}=${data[key]}`);
    index != datasize - 1 && (initial = initial.concat('&'));
  });
  console.log(initial, 'MyqueryString');
  return initial;
};

console.log(getqueryParam(data))//You can get the query string here

If you have baseUrl means to get full query use 

baseUrl concat (getqueryParam(数据)。