Query-string encoding of a Javascript Object

2018-12-31 04:49发布

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 other frameworks - just plain Javascript :)

30条回答
余生无你
2楼-- · 2018-12-31 05:47
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 ) {
  return '?'+Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&')
}
查看更多
与君花间醉酒
3楼-- · 2018-12-31 05:47

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

const encoded = Object.entries(obj).map((k, v) => `${k}=${encodeURIComponent(v)}`).join("&");
查看更多
谁念西风独自凉
4楼-- · 2018-12-31 05:48

This one skips null/undefined values

export function urlEncodeQueryParams(data) {
    const params = Object.keys(data).map(key => data[key] ? `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}` : '');
    return params.filter(value => !!value).join('&');
}
查看更多
唯独是你
5楼-- · 2018-12-31 05:49

jQuery has a function for this, jQuery.param(), if you're already using it you can use that: http://api.jquery.com/jquery.param/

example:

var params = { width:1680, height:1050 };
var str = jQuery.param( params );

str now contains width=1680&height=1050

查看更多
笑指拈花
6楼-- · 2018-12-31 05:49

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("&");
}
查看更多
浪荡孟婆
7楼-- · 2018-12-31 05:51

In ES7 you can write this in one line:

const serialize = (obj) => (Object.entries(obj).map(i => [i[0], encodeURIComponent(i[1])].join('=')).join('&'))
查看更多
登录 后发表回答