javascript - 将 URL 查询参数转换为格式化数组的最佳方法
问题描述
我有一个带有查询参数的 URL,看起来像这样
&rootDimension=availability%253AOnlinepipsymbBrand%253ADell%253ABICpipsymbProduct%2520Rating%254A3%2520stars%2520and%2520above
我正在做一个decodeURIComponent(query.rootRootdimension).split("pipsymb")
返回一个看起来像这样的数组
["availability:Online", "Brand:Dell:BIC", "Product Rating:4 stars and above"]
我基本上需要检查数组并删除不是“品牌”或“产品评级”的键。所以在这种情况下它应该返回一个数组["Brand:Dell:BIC", "Product Rating:4 stars and above"]
。
如果产品评级为“4 星及以上”,则应将其替换为“最高评级”,否则应仅保留评级["Brand:Dell:Bic", "Product Rating: "3 stars and above"]
。该数组应如下所示
["Brand:Dell:BIC", "Product Rating:Top Rated"]
。
我正在寻找的结果是["Dell", "Bic", "Top Rated"]
我尝试了下面的功能和其他一些东西,但我没有得到我想要的东西。感谢您的帮助/建议!
const getRefinements = (query) => {
decodeURIComponent(query.rootDimension).split("pipsymb").reduce((obj, str) => {
let strParts = str.split(/::|:/);
if (strParts[0] && strParts[1]) {
obj[strParts[0].replace(/\s+/g, "")] = strParts[1];
return Object.values(pick(obj, ["Brand", "ProductRating"]))
}
})
}
解决方案
尝试以下操作:
let query = decodeURIComponent(
"&rootDimension=availability%253AOnlinepipsymbBrand%253ADell%253ABICpipsymbProduct%2520Rating%254A3%2520stars%2520and%2520above"
);
query = query
.replace(/%3A/g, ":")
.replace(/%20/g, " ")
.replace(/%4A/g, "J");
const productDetails = query.split("pipsymb");
let brandPart = productDetails
.find(item => item.match("Brand"))
.replace("Brand:", "")
.split(":");
let productRating = productDetails
.find(item => item.match("Product Rating"))
.split("J")[1];
if (productRating.includes("4")) {
productRating = "Top Rated";
}
const result = [...brandPart, productRating];
console.log(result);
输出
['Dell', 'BIC', '3 stars and above']
推荐阅读
- r - 如何在测试中设置最大失败次数?
- javascript - 带有重音符号的正则表达式搜索结果突出显示
- reactjs - mini-css-extract-plugin:仅在导入 JS 文件时导入 CSS 文件
- r - 与原始栅格相比,tmap 正在为裁剪的栅格图层绘制不同的图例(值范围?)
- reactjs - Mobx - 更改依赖项列表中的项目时未执行 UseEffect 挂钩
- javascript - 如何包装动态的内部 div?
- pine-script - 如何编写 If 语句函数代码来搜索 Pinescript 中的源变量中是否包含特定文本?
- python - 如何使用 Python 请求登录网页?
- php - 使用 nginx 配置文件在 wordpress 中保护 wp-login.php
- powershell - Powershell在一个Select-Object中获取不同级别的节点值