Home > Software design >  How to filter API category in React
How to filter API category in React

Time:01-03

That's my 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"
},

How can I filter it and only get the products which have catogery featured?

CodePudding user response:

Use the array filter method.

your_array.filter(item => item['category'] === "featured");

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

This has nothing to do with react by the way. It's vanilla javascript.

CodePudding user response:

You can use the filter method.

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)

CodePudding user response:

There are many ways to do this. Here, I have two major ways to solve this:

  1. using filter:

    array.filter(data => data.category === "featured")
    
  2. using find:

    array.find(data => data.category === "featured")
    

The major difference is that the Filter method will return the array object. i.e [{_uId: ...}] Whereas, Find method will return the object only. i.e {_uId:...}

  • Related