使用Lodash根据价格区间筛选所有产品对象
按价格区间筛选产品对象集合的解决方案
嘿,这个需求很常见,用JavaScript的数组方法就能轻松搞定!我给你整理了几种实用的实现方式,直接就能套用在你的产品集合上。
首先,先补全你给出的products数组(假设Product 4的价格为250.00):
const products = [ { name: 'Product 1', usage: 'Home', skill: 'Easy', color: 'blue', price: 100.00 }, { name: 'Product 2', usage: 'Home', skill: 'Intermediate', color: 'red', price: 120.00 }, { name: 'Product 3', usage: 'Office', skill: 'Intermediate', color: 'green', price: 190.00 }, { name: 'Product 4', usage: 'Office', skill: 'Advanced', color: 'black', price: 250.00 } ];
方法一:复用性强的筛选函数
最直接的方式是用Array.filter()方法,封装成一个可复用的函数,这样你可以随时传入不同的价格区间:
function filterProductsByPrice(minPrice, maxPrice) { // 处理用户可能传入的minPrice大于maxPrice的情况 if (minPrice > maxPrice) { [minPrice, maxPrice] = [maxPrice, minPrice]; } // 筛选价格在区间内的产品(包含边界值) return products.filter(product => product.price >= minPrice && product.price <= maxPrice); }
使用示例
比如你要筛选价格在100到200之间的产品:
const filteredProducts = filterProductsByPrice(100, 200); console.log(filteredProducts);
输出结果会是:
[ { name: 'Product 1', usage: 'Home', skill: 'Easy', color: 'blue', price: 100 }, { name: 'Product 2', usage: 'Home', skill: 'Intermediate', color: 'red', price: 120 }, { name: 'Product 3', usage: 'Office', skill: 'Intermediate', color: 'green', price: 190 } ]
方法二:简洁的一次性筛选
如果只是单次使用,不需要封装函数,可以直接写箭头函数版本:
// 定义价格区间 const minPrice = 120; const maxPrice = 250; // 直接筛选 const filtered = products.filter(p => p.price >= minPrice && p.price <= maxPrice);
额外提示
- 如果你需要排除边界值,只需要把判断条件里的
>=改成>,<=改成<即可 - 如果你的产品集合里可能存在
price为undefined或者非数字的情况,可以在筛选时加个判断,避免出错:
return typeof product.price === 'number' && product.price >= minPrice && product.price <= maxPrice;
内容的提问来源于stack exchange,提问作者Faizan Saiyed
相关产品推荐
相关产品推荐

