问题描述
["action=order_changed","orderId=10002701","brandId=5983e481fab80f4198691bbc","unitId=5e801b6ddd43bb20cc2e5469","isRepeat=false","isdisplay=true"]
我想通过拆分=
for Array中的每个项目来创建对象。
我期望的对象是:
{
action: "order_changed",orderId: 10002701,brandId: "5983e481fab80f4198691bbc",unitId: "5e801b6ddd43bb20cc2e5469",isRepeat: false,isdisplay: true
}
我使用过foreach,而不是大量减少练习,因此我的代码很糟糕。
splitStringParameter(str: string) {
let stringQuery = str.split('?').pop();
let arrayQuery = stringQuery.split('&');
let object = {};
arrayQuery.forEach(item => {
item.split("=");
object[item[0]] = item[1]
})
}
非常感谢
解决方法
您可以使用String.split
拆分键和值,然后使用Array.prototype.reduce
将它们连接到新对象中。
const input = ["action=order_changed","orderId=10002701","brandId=5983e481fab80f4198691bbc","unitId=5e801b6ddd43bb20cc2e5469","isRepeat=false","isDisplay=true"];
const output = input.reduce((acc,cur) => {
const curArr = cur.split("=");
const key = curArr[0];
const value = curArr.splice(1).join("=");
acc[key] = value;
return acc;
},{});
console.log(output);
,
更新(现在您已提供代码):
您的初始输入看起来像是查询字符串-检出URLSearchParams (MDN):
var paramsString = "q=URLUtils.searchParams&topic=api"; var searchParams = new URLSearchParams(paramsString); //Iterate the search parameters. for (let p of searchParams) { console.log(p); } searchParams.has("topic") === true; // true searchParams.get("topic") === "api"; // true searchParams.getAll("topic"); // ["api"] searchParams.get("foo") === null; // true searchParams.append("topic","webdev"); searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev" searchParams.set("topic","More webdev"); searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev" searchParams.delete("topic"); searchParams.toString(); // "q=URLUtils.searchParams"
const a = ["action=order_changed","isDisplay=true"];
const transform = v => {
if (v === 'false') {
return false;
}
if (v === 'true') {
return true;
}
return v;
}
const o = a.reduce((res,e) => {
const [key,val] = e.split('=');
res[key] = transform(val);
return res;
},{});
console.log(o);