Home > Back-end >  How to select the array item (array of objects) based upon a particular attribute
How to select the array item (array of objects) based upon a particular attribute

Time:06-24

I have the following array of objects I am trying to filter the products by size in such a way such that all the products of the specific size selected by user only get rendered as you normally see it happening on an ecommerce website.

So for example if I select the size S, I only want the products to render which have the size "S" available in the inventory

part1 to grab the size picked up by the user

const sizeFilterHandler = (event) => {
    console.log(event.target.value);
    setSizeFilter(event.target.value);
  };

part2 to grab the size picked up by the user

          onChange={sizeFilterHandler}
          className="form-select mb-3"
          aria-label=".form-select-lg example"
        >
          <option selected>Size</option>
          <option value="S">S</option>
          <option value="M">M</option>
          <option value="L">L</option>
          <option value="XL">XL</option>
          <option value="XXL">XXL</option>
          <option value="XXXL">XXXL</option>
        </select>
"inventoryInfo": [
            {
                "skuId": 47638228,
                "label": "S",
                "inventory": 227,
                "available": true
            },
            {
                "skuId": 47638227,
                "label": "M",
                "inventory": 330,
                "available": true
            },
            {
                "skuId": 47638224,
                "label": "L",
                "inventory": 325,
                "available": true
            },
            {
                "skuId": 47638225,
                "label": "XL",
                "inventory": 313,
                "available": true
            },
            {
                "skuId": 47638226,
                "label": "XXL",
                "inventory": 146,
                "available": true
            },
            {
                "skuId": 47638223,
                "label": "3XL",
                "inventory": 80,
                "available": true
            }
        ],

CodePudding user response:

You should be able to use the array filter function. Something like

inventoryToDisplay = inventoryInfo.filter(inventoryItem => inventoryItem.label === event.target.value)

CodePudding user response:

Filter and Map

  return (
    <div className="App">
      {/* XL is your value from setFilter */}
      {inventoryInfo
        .filter((item) => item.label === 'XL' && item.available === true)
        .map((element, index) => (
          <>
            <div key={index}>{element.skuId}</div>
            <div key={index}>{element.label}</div>
            <div key={index}>{element.inventory}</div>
            <div key={index}>{element.available}</div>
          </>
        ))}
    </div>
  );
  • Related