Query-string encoding of a Javascript Object

前端 未结 30 2950
渐次进展
渐次进展 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 00:57

    Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&')
    

    Edit: I like this one-liner, but I bet it would be a more popular answer if it matched the accepted answer semantically:

    function serialize( obj ) {
        let str = '?' + Object.keys(obj).reduce(function(a, k){
            a.push(k + '=' + encodeURIComponent(obj[k]));
            return a;
        }, []).join('&');
        return str;
    }
    

提交回复
热议问题