如何最方便的将{ id: 111, name: 'aaa'}
转换成"id=111&name=aaa"
如何最方便的将{ id: 111, name: 'aaa'}
转换成"id=111&name=aaa"
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;
};
10 回答11.2k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
1 回答6k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决