Query-string encoding of a Javascript Object

前端 未结 30 2911
渐次进展
渐次进展 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:52

    A little bit look better

    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("&");
    }
    
    0 讨论(0)
  • 2020-11-22 00:53

    Well, everyone seems to put his one-liner here so here goes mine:

    const encoded = Object.entries(obj).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
    
    0 讨论(0)
  • 2020-11-22 00:53

    I have a simpler solution that does not use any third-party library and is already apt to be used in any browser that has "Object.keys" (aka all modern browsers + edge + ie):

    In ES5

    function(a){
        if( typeof(a) !== 'object' ) 
            return '';
        return `?${Object.keys(a).map(k=>`${k}=${a[k]}`).join('&')}`;
    }
    

    In ES3

    function(a){
        if( typeof(a) !== 'object' ) 
            return '';
        return '?' + Object.keys(a).map(function(k){ return k + '=' + a[k] }).join('&');
    }
    
    0 讨论(0)
  • 2020-11-22 00:54

    ok, it's a older post but i'm facing this problem and i have found my personal solution.. maybe can help someone else..

         function objToQueryString(obj){
            var k = Object.keys(obj);
            var s = "";
            for(var i=0;i<k.length;i++) {
                s += k[i] + "=" + encodeURIComponent(obj[k[i]]);
                if (i != k.length -1) s += "&";
            }
            return s;
         };
    
    0 讨论(0)
  • 2020-11-22 00:55

    Addition for accepted solution, this works with objects & array of objects:

    parseJsonAsQueryString = function (obj, prefix, objName) {
        var str = [];
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                var v = obj[p];
                if (typeof v == "object") {
                    var k = (objName ? objName + '.' : '') + (prefix ? prefix + "[" + p + "]" : p);
                    str.push(parseJsonAsQueryString(v, k));
                } else {
                    var k = (objName ? objName + '.' : '') + (prefix ? prefix + '.' + p : p);
                    str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
                    //str.push(k + "=" + v);
                }
            }
        }
        return str.join("&");
    }
    

    Also have added objName if you're using object parameters like in asp.net mvc action methods.

    0 讨论(0)
  • 2020-11-22 00:56

    With Node.js v6.6.3

    const querystring = require('querystring')
    
    const obj = {
      foo: 'bar',
      baz: 'tor'
    }
    
    let result = querystring.stringify(obj)
    // foo=bar&baz=tor
    

    Reference: https://nodejs.org/api/querystring.html

    0 讨论(0)
提交回复
热议问题