在软件开发中,经常需要根据特定条件过滤对象数组。假设我们有一个包含多个对象的数组,每个对象代表一个商品,具有价格和其他属性。我们需要根据设置的价目表价格范围和其他选项来过滤这些对象。
假设我们有一个商品数组,每个商品对象包含name
、price
、brand
等属性。我们需要根据价格范围和其他选项(如品牌)来过滤这些商品。
// 示例商品数组
const products = [
{ name: 'Product A', price: 100, brand: 'Brand X' },
{ name: 'Product B', price: 200, brand: 'Brand Y' },
{ name: 'Product C', price: 150, brand: 'Brand X' },
{ name: 'Product D', price: 300, brand: 'Brand Z' }
];
// 过滤函数
function filterProducts(products, minPrice, maxPrice, brand) {
return products.filter(product => {
const withinPriceRange = product.price >= minPrice && product.price <= maxPrice;
const matchesBrand = brand ? product.brand === brand : true;
return withinPriceRange && matchesBrand;
});
}
// 使用示例
const filteredProducts = filterProducts(products, 100, 200, 'Brand X');
console.log(filteredProducts);
通过上述方法,可以有效地根据设置的价目表价格范围和其他选项过滤对象数组,满足各种应用场景的需求。
领取专属 10元无门槛券
手把手带您无忧上云