VueJS中如何结合多条件与价格区间过滤JSON数组
嘿,我来帮你优化这个过滤逻辑,让它既能处理普通的键值匹配,又能支持价格区间的筛选~
核心思路
原来的过滤函数只处理了键值严格相等的情况,但expected_selected里的Price是一个区间数组([最小值, 最大值]),我们需要给这个字段单独做区间判断,其他字段保持原有的匹配逻辑即可。
修改后的完整代码
var boats = [{ Price: 599900, BrandName: "FLIPPER", BoatYear: 2020, }, { Price: 97e3, BrandName: "MICORE", BoatYear: 2020, }, { Price: 189300, BrandName: "LINDER", BoatYear: 2020, }, { Price: 396900, BrandName: null, BoatYear: 2020, }, { Price: 334900, BrandName: "MICORE", BoatYear: 2019, }, { Price: 138700, BrandName: "HR", BoatYear: 2020, }, { Price: 178900, BrandName: "HR", BoatYear: 2020, }, { Price: 348900, BrandName: "HR", BoatYear: 2020, }, { Price: 285800, BrandName: "HR", BoatYear: 2020, }, { Price: 186900, BrandName: "MICORE", BoatYear: 2019, }, { Price: 276800, BrandName: "MICORE", BoatYear: 2020, }, { Price: 518900, BrandName: "SILVER", BoatYear: 2020, }, { Price: 226900, BrandName: "MICORE", BoatYear: 2020, }, { Price: 132600, BrandName: "LINDER", BoatYear: 2020, }, { Price: 137200, BrandName: "LINDER", BoatYear: 2020, }, { Price: 366900, BrandName: "SILVER", BoatYear: 2020, }, { Price: 365900, BrandName: "SILVER", BoatYear: 2020, }, { Price: 247900, BrandName: "SILVER", BoatYear: 2020, }]; var expected_selected = { BoatYear: 2020, BrandName: 'LINDER', Price: [0, 138000] }; // 修改后的过滤函数 const filteredBoats = boats.filter(item => { // 遍历所有筛选条件 for (const [key, value] of Object.entries(expected_selected)) { if (key === 'Price') { // 处理价格区间:检查item的Price是否在[min, max]范围内 const [minPrice, maxPrice] = value; if (item.Price < minPrice || item.Price > maxPrice) { return false; } } else { // 处理普通键值匹配:和原逻辑一致,不匹配就过滤 if (item[key] === undefined || item[key] !== value) { return false; } } } // 所有条件都满足则保留 return true; }); console.log(`Results: ${JSON.stringify(filteredBoats)}`);
代码说明
- 遍历筛选条件:用
Object.entries()把expected_selected转换成键值对数组,方便遍历每个筛选条件。 - 价格区间处理:当遇到
Price键时,解构出最小值和最大值,判断船只价格是否在区间内,不在就直接返回false过滤掉。 - 普通字段匹配:其他字段(比如
BoatYear、BrandName)保持原有的严格相等逻辑,确保只有完全匹配的船只才会被保留。
运行结果
执行后会得到符合条件的2条数据:
Results: [{"Price":132600,"BrandName":"LINDER","BoatYear":2020},{"Price":137200,"BrandName":"LINDER","BoatYear":2020}]
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

