首页 > 解决方案 > 将 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"]))
            }
   })
}

标签: javascriptreactjsredux

解决方案


尝试以下操作:

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']

推荐阅读