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

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


当前回答

Use:

const objectToQueryParams = (o = {}) =>
  Object.entries(o)
    .map((p) => `${encodeURIComponent(p[0])}=${encodeURIComponent(p[1])}`)
    .join("&");

参考以下要点了解更多信息: https://gist.github.com/bhaireshm

其他回答

看起来好一点

objectToQueryString(obj, prefix) {
    return Object.keys(obj).map(objKey => {
        if (obj.hasOwnProperty(objKey)) {
            const key = prefix ? `${prefix}[${objKey}]` : objKey;
            const value = obj[objKey];

            return typeof value === "object" ?
                this.objectToQueryString(value, key) :
                `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
        }

        return null;
    }).join("&");
}

只需使用以下方法:

encodeURIComponent(JSON.stringify(obj))

// elastic search example let story ={ "query": { "bool": { "must": [ { "term": { "revision.published": 0, } }, { "term": { "credits.properties.by.properties.name": "Michael Guild" } }, { "nested": { "path": "taxonomy.sections", "query": { "bool": { "must": [ { "term": { "taxonomy.sections._id": "/science" } }, { "term": { "taxonomy.sections._website": "staging" } } ] } } } } ] } } } const whateva = encodeURIComponent(JSON.stringify(story)) console.log(whateva)

Use:

const toQueryString = obj => "?".concat(Object.keys(obj).map(e => `${encodeURIComponent(e)}=${encodeURIComponent(obj[e])}`).join("&"));

const data = {
  offset: 5,
  limit: 10
};

toQueryString(data); // => ?offset=5&limit=10

或者使用预定义的特性

const data = {
  offset: 5,
  limit: 10
};

new URLSearchParams(data).toString(); // => ?offset=5&limit=10

Note

如果不存在,上述两个方法都将值设置为null。 如果你不想设置查询参数值为空,那么使用:

const toQueryString = obj => "?".concat(Object.keys(obj).map(e => obj[e] ? `${encodeURIComponent(e)}=${encodeURIComponent(obj[e])}` : null).filter(e => !!e).join("&"));


const data = {
  offset: null,
  limit: 10
};

toQueryString(data); // => "?limit=10" else with above methods "?offset=null&limit=10"

你可以自由使用任何方法。

是这样的:

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

下面是一个简单的实现,获取一个对象并将其转换为查询参数字符串:

export function objectToQueryParams(queryParams: object): string {
  return queryParams ?
    Object.entries(queryParams).reduce((acc, [key, val], index) => {
      const sign = index === 0 ? '?' : '&';
      acc += `${sign}${encodeURIComponent(key)}=${encodeURIComponent(val)}`;
      return acc;
    }, '')
    : '';
}