方法1:
const data = {
id: 1,
name: "张三",
age: 22
}
let params = ""
/* Object.entries()方法返回一个数组,数组的每一个元素是对象的自有的可枚举属性的键值对,但不包括Symbol值的属性。
形如:[[key1, value1], [key2, value2], ... [keyn, valuen]] */
console.log(Object.entries(data)) // [ [ 'id', 1 ], [ 'name', '张三' ], [ 'age', 22 ] ]
for( const [key, value] of Object.entries(data)) {
params += `${key}=${value}&`
}
if(params) {
params = params.substring(0, params.length-1)
}
console.log(params) // id=1&name=张三&age=22
方法2:
const data = {
id: 1,
name: "张三",
age: 22
}
function getParams(obj = {}) {
let temp = Object.entries(obj)
let params = ""
for( const [key, value] of temp) {
params += `${params ? '&' : '?'}${key}=${value}`
}
return params
}
console.log(getParams(data)) // ?id=1&name=张三&age=22