Query-string encoding of a Javascript Object

前端 未结 30 2925
渐次进展
渐次进展 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("&");
    }
    

提交回复
热议问题