js转换问题:{ id: 111, name: 'aaa'}转换成"id=111&name=aaa"

如何最方便的将{ id: 111, name: 'aaa'}转换成"id=111&name=aaa"

阅读 4.8k
5 个回答
function toUrlSearch (obj) {
    return new URLSearchParams(obj).toString()
}

nodejs 自带 的模块 querystring; 前端应该有类似的库

var querystring = require('querystring');

var obj = { id: 111, name: 'aaa'};  

console.log(querystring.stringify(obj)); // 转换成"id=111&name=aaa"

1.0版本

function jsonToQuery(json) {
    let result = [];
    for (let key in json) {
         result.push(key + '=' + json[key]);
    }
    return result.join('&');
};

2.0版

function jsonToQuery(json, replace){
let result = [];
replace = replace || function(value){
    return value;
}

for(let key in json){
    let item = json[key];

    result.push(key + '=' + replace(json[key]));
}
return result.join('&');

}

/**
 * 判断是否为object
 * @param obj
 * @returns {boolean}
 */
const isPlainObject = obj => {
  if (typeof obj !== 'object' || obj === null) return false;

  let proto = obj;
  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto);
  }
  return Object.getPrototypeOf(obj) === proto;
};

/**
 * 判断是否为object或者array
 * @param obj
 */
const isObjectOrArray = obj =>
  obj !== null && (Array.isArray(obj) || isPlainObject(obj));

/**
 * 把data转化为query string
 * @param data
 * @returns {string}
 */
const dataToQueryString = (data = null) => {
  let queryString = '';
  if (data !== null) {
    const propsArray = Object.keys(data);
    const queryArray = [];
    propsArray.forEach(props => {
      const value = data[props];
      if (value !== undefined && value !== '') {
        if (isObjectOrArray(value)) {
          queryArray.push(`${props}=${encodeURI(JSON.stringify(value))}`);
        } else {
          queryArray.push(`${props}=${value}`);
        }
      }
    });
    queryString = queryArray.join('&');
  }
  return queryString;
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题