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

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


当前回答

我建议使用URLSearchParams接口:

const searchParams = new URLSearchParams(); Const params = {foo: "hi there", bar: "100%"}; 种(params)。forEach(key => searchParams。追加(关键,params[主要])); console.log (searchParams.toString ())

或者像这样将搜索对象传递给构造函数:

Const params = {foo: "hi there", bar: "100%"}; const queryString = new URLSearchParams(params).toString(); console.log(参数);

其他回答

在讨论了一些最重要的答案之后,我编写了另一个实现,它也可以处理一些边缘情况

function serialize(params, prefix) {                
    return Object.entries(params).reduce((acc, [key, value]) => {
        // remove whitespace from both sides of the key before encoding
        key = encodeURIComponent(key.trim());

        if (params.constructor === Array ) {
          key = `${prefix}[]`;
        } else if (params.constructor === Object) {
          key = (prefix ? `${prefix}[${key}]` : key);
        }

        /**
         *  - undefined and NaN values will be skipped automatically
         *  - value will be empty string for functions and null
         *  - nested arrays will be flattened
         */
        if (value === null || typeof value === 'function') {
            acc.push(`${key}=`);
        } else if (typeof value === 'object') {
            acc = acc.concat(serialize(value, key));
        } else if(['number', 'boolean', 'string'].includes(typeof value) && value === value) { // self-check to avoid NaN
            acc.push(`${key}=${encodeURIComponent(value)}`);
        }

        return acc;
    }, []);
}

function objectToQueryString(queryParameters) {
    return queryParameters ? serialize(queryParameters).join('&'): '';
}

let x = objectToQueryString({
    foo: 'hello world',
    bar: {
      blah: 123,
      list: [1, 2, 3],
        'nested array': [[4,5],[6,7]] // will be flattened
    },
    page: 1,
    limit: undefined, // field will be ignored
    check: false,
    max: NaN, // field will be ignored
    prop: null,
    ' key value': 'with spaces' // space in key will be trimmed out
});
  
console.log(x); // foo=hello%20world&bar[blah]=123&bar[list][]=1&bar[list][]=2&bar[list][]=3&bar[nested%20array][][]=4&bar[nested%20array][][]=5&bar[nested%20array][][]=6&bar[nested%20array][][]=7&page=1&check=false&prop=&key%20value=with%20spaces

只使用URLSearchParams,这适用于当前所有浏览器

new URLSearchParams(object).toString()

Use:

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

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

这个函数跳过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('&');
}

只需使用以下方法:

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)