Flatten a javascript object to pass as querystring

前端 未结 12 1954
半阙折子戏
半阙折子戏 2020-12-04 23:24

I have a javascript object that I need to flatten into a string so that I can pass as querystring, how would I do that? i.e:

{ cost: 12345, insertBy: \'testUse

12条回答
  •  佛祖请我去吃肉
    2020-12-05 00:00

    ES6 version of Jrop's answer (also parses nested params)

    const toQueryString = (obj, urlEncode = false) => {
      if (!obj) return null;
      const flattenObj = (x, path = []) => {
        const result = [];
        Object.keys(x).forEach((key) => {
          if (!Object.prototype.hasOwnProperty.call(x, key)) return;
          const newPath = path.slice();
          newPath.push(key);
          let vals = [];
          if (typeof x[key] === 'object') {
            vals = flattenObj(x[key], newPath);
          } else {
            vals.push({ path: newPath, val: x[key] });
          }
          vals.forEach((v) => {
            return result.push(v);
          });
        });
        return result;
      };
    
      let parts = flattenObj(obj);
      parts = parts.map((varInfo) => {
        if (varInfo.path.length === 1) {
          varInfo.path = varInfo.path[0]; // eslint-disable-line no-param-reassign
        } else {
          const first = varInfo.path[0];
          const rest = varInfo.path.slice(1);
          varInfo.path = `${first}[${rest.join('][')}]`; // eslint-disable-line no-param-reassign
        }
        return varInfo;
      });
    
      const queryString = parts.map((varInfo) => {
        return `${varInfo.path}=${varInfo.val}`;
      }).join('&');
      if (urlEncode) {
        return encodeURIComponent(queryString);
      }
      return queryString;
    };
    

提交回复
热议问题