Query-string encoding of a Javascript Object

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

    ES6 SOLUTION FOR QUERY STRING ENCODING OF A JAVASCRIPT OBJECT

    const params = {
      a: 1,
      b: 'query stringify',
      c: null,
      d: undefined,
      f: '',
      g: { foo: 1, bar: 2 },
      h: ['Winterfell', 'Westeros', 'Braavos'],
      i: { first: { second: { third: 3 }}}
    }
    
    static toQueryString(params = {}, prefix) {
      const query = Object.keys(params).map((k) => {
        let key = k;
        const value = params[key];
    
        if (!value && (value === null || value === undefined || isNaN(value))) {
          value = '';
        }
    
        switch (params.constructor) {
          case Array:
            key = `${prefix}[]`;
            break;
          case Object:
            key = (prefix ? `${prefix}[${key}]` : key);
            break;
        }
    
        if (typeof value === 'object') {
          return this.toQueryString(value, key); // for nested objects
        }
    
        return `${key}=${encodeURIComponent(value)}`;
      });
    
      return query.join('&');
    }
    

    toQueryString(params)

    "a=1&b=query%20stringify&c=&d=&f=&g[foo]=1&g[bar]=2&h[]=Winterfell&h[]=Westeros&h[]=Braavos&i[first][second][third]=3"
    

提交回复
热议问题