Ese es mi JSON:
{ "_id": "61d18b98d489dfcff325843d", "productName": "Cantilever chair", "productImg": "https://i.ibb.co/k5hNxd3/image-1168.png", "price": 42, "productCode": "Y101", "category": "featured", "review": 4, "totalReview": 42, "Color": "White", "description": "LumbarSupport Office Chair Meeting chair designed with curved contour giving optimalsupport to your lumbar and keep your spine aligned properly. Ergonomicreclining lean back design makes it extremely comfort.CoolingMesh Back & Extra Comfort Cushion Added comfort with breathable fabric that you can relax into, added high density mesh-covered foam seat cushion forextra comfort. Embrace a pain free working day.Office ChairDesign in Style Well design in front of an office desk, reception room oraround conference table. Offers professional appearance in any office setting,making it easy for colleagues and clients to have a seat with our desk chair.EasyAssemble You just need to tighten the screws then you will get an aestheticoffice chair. Tips on assemble: leave the chair back slack till all screwsaligned then tighten" },¿Cómo puedo filtrarlo y obtener solo los productos que tienen una categoría destacada?
Utilice el método de filtro de matriz.
your_array.filter(item => item['category'] === "featured");https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Esto no tiene nada que ver con reaccionar por cierto. Es javascript vainilla.
Puede utilizar el método de filtro.
const items = [ { _id: "61d18b98d489dfcff325843d", productName: "Cantilever chair", productImg: "https://i.ibb.co/k5hNxd3/image-1168.png", price: 42, productCode: "Y101", category: "featured", review: 4, totalReview: 42, Color: "White", }, { _id: "61d18b98d489dfcff325843d", productName: "Cantilever chair", productImg: "https://i.ibb.co/k5hNxd3/image-1168.png", price: 42, productCode: "Y101", category: "something", review: 4, totalReview: 42, Color: "White", }, ]; const filteredItems = items.filter((item) => item.category === "featured"); console.log("filteredItems", filteredItems);Hay muchas maneras de hacer esto. Aquí, tengo dos formas principales de resolver esto:
usando filtro:
array.filter(data => data.category === "featured")usando encontrar:
array.find(data => data.category === "featured")La principal diferencia es que el método Filter devolverá el objeto de matriz. es decir, [{_uId: ...}] Mientras que el método Find devolverá solo el objeto. es decir, {_uId:...}