Estoy creando una filtración en el proyecto de comercio electrónico. tengo datos como
const gender = ["male"] const brand = ["adidas","nike"] const price =[100] //note: gender,brand,price are not static array, it can single element or more than that. const allProducts = [ {brand:"puma",gender:"male",price:50}, {brand:"nike",gender:"male",price:90}, {brand:"adidas",gender:"female",price:110}, {brand:"adidas",gender:"male",price:95},]Ahora, quiero filtrar todos los productos según el género, la marca y el precio. Debería obtener todos los productos que tengan género masculino con la marca Adidas y Nike y un precio inferior a 100.
He conseguido el resultado solo para la marca, así
const[filteredprod,setFilteredprod]=useState() allProducts.forEach((value)=>{ for(var i=0;i<brand.length;i++){ if(value.brand===brand?.[i]) {setFilteredProd = value )}} })Pero quiero hacer precio de género de marca simultáneamente y obtener el producto. ¿Cómo puedo hacer eso? ¡¡Gracias!!
allProducts.filter((item)=>(item.brand === 'adidas' || item.brand === 'nike') && item.price<100 && item.gender === 'male');
Para verificar dinámicamente la condición,
allProducts.filter((item)=>brand.includes(item.brand)&& item.price<price[0] && gender.includes(item.gender));
Puede agregar otra condición a su instrucción if dentro de su bucle forEach.
allProducts.forEach((value)=>{ for(var i=0;i<brand.length;i++){ if(value.brand===brand?.[i] && value.gender === 'male' && value.price <100) {setFilteredProd = value )}} })Sin embargo, la práctica más estándar sería usar el filtro del método de matriz.
allProducts.filter(({ brand, price, gender) => (brand === 'adidas' || brand === 'nike') && price < 100 && gender === 'male');Prueba esto
const gender = ["male"] const brand = ["adidas", "nike"] const price = [100] const allProducts = [{ brand: "puma", gender: "male", price: 50 }, { brand: "nike", gender: "male", price: 90 }, { brand: "adidas", gender: "female", price: 110 }, { brand: "adidas", gender: "male", price: 95 }, ] console.log(allProducts.filter(product => { if (product.gender === gender[0] && product.price < price[0] && (product.brand === brand[0] || product.brand === brand[1])) { return true } return false }))