作者:潇潇洒洒牛仔_584 | 来源:互联网 | 2022-12-07 06:10
我使用.map()从表单中的值对象创建查询参数.
let object = {
"selectedPriority": "9",
"selectedShipOption": "Private Label",
"selectedCustomerStatus": "No",
"selectedColdOptions": [],
"selectedDistributionOptions": ["Retail"],
"selectedPackagingOption": "Lid",
"selectedPrepOption": "Hot Water",
"productParams": ["Kosher\n"],
"productAppearance": "Grill Marks",
"storage": "CAP",
"preservatives": "Only natural preservatives"
}
Object.keys(object).map((key, index) => {
console.log(`?${key}=${object[key]}`)
});
现在我已经操作了每个对象和键,我想将它们连接在一起以创建一个查询字符串.
我怎样才能做到这一点?
1> CertainPerfo..:
你.map
现在实际上没有映射任何东西 - 它只是console.log
ging和返回undefined
.
如果需要查询字符串,则只应?
在第一个之前添加a ,并&
在所有参数之间添加.所以,你可以join
通过&
并添加?
到开头.
您也可以考虑使用Object.entries
同时获取密钥和值,而不是必须引用object[key]
.
您还应该使用encodeURIComponent
将不安全的URL(如普通空格)转换为正确的转义序列(如%20
):
const object = {
"selectedPriority": "9",
"selectedShipOption": "Private Label",
"selectedCustomerStatus": "No",
"selectedColdOptions": [],
"selectedDistributionOptions": ["Retail"],
"selectedPackagingOption": "Lid",
"selectedPrepOption": "Hot Water",
"productParams": ["Kosher\n"],
"productAppearance": "Grill Marks",
"storage": "CAP",
"preservatives": "Only natural preservatives"
}
const result = '?' + Object.entries(object).map(([key, value]) => {
return `${key}=${encodeURIComponent(value)}`
}).join('&');
console.log(result);