Query-string encoding of a Javascript Object

前端 未结 30 2958
渐次进展
渐次进展 2020-11-22 00:23

Do you know a fast and simple way to encode a Javascript Object into a string that I can pass via a GET Request?

No jQuery, no

30条回答
  •  花落未央
    2020-11-22 01:02

    Here's a concise & recursive version with Object.entries. It handles arbitrarily nested arrays, but not nested objects. It also removes empty elements:

    const format = (k,v) => v !== null ? `${k}=${encodeURIComponent(v)}` : ''
    
    const to_qs = (obj) => {
        return [].concat(...Object.entries(obj)
                           .map(([k,v]) => Array.isArray(v) 
                              ? v.map(arr => to_qs({[k]:arr})) 
                              : format(k,v)))
               .filter(x => x)
               .join('&');
    }
    

    E.g.:

    let json = { 
        a: [1, 2, 3],
        b: [],              // omit b
        c: 1,
        d: "test&encoding", // uriencode
        e: [[4,5],[6,7]],   // flatten this
        f: null,            // omit nulls
        g: 0
    };
    
    let qs = to_qs(json)
    
    => "a=1&a=2&a=3&c=1&d=test%26encoding&e=4&e=5&e=6&e=7&g=0"
    

提交回复
热议问题