鍍金池/ 問答/Java  HTML/ js轉(zhuǎn)換問題:{ id: 111, name: 'aaa'}轉(zhuǎn)換成"i

js轉(zhuǎn)換問題:{ id: 111, name: 'aaa'}轉(zhuǎn)換成"id=111&name=aaa"

如何最方便的將{ id: 111, name: 'aaa'}轉(zhuǎn)換成"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('&');

}

2017年12月1日 17:16
編輯回答
玄鳥

nodejs 自帶 的模塊 querystring; 前端應(yīng)該有類似的庫

var querystring = require('querystring');

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

console.log(querystring.stringify(obj)); // 轉(zhuǎn)換成"id=111&name=aaa"
2017年5月21日 17:58
編輯回答
敢試

qs模塊最方便
https://github.com/ljharb/qs

2017年4月9日 14:44
編輯回答
遲月
/**
 * 判斷是否為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轉(zhuǎn)化為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;
};
2017年1月18日 02:43
編輯回答
尐飯團
function toUrlSearch (obj) {
    return new URLSearchParams(obj).toString()
}
2018年2月15日 01:31