1

I just wanted to filter the state products object item based on the value(variable present in the state)

I have tried to get all products from the API and stored in product state

here is my state

state = {
        isLoading: false,
        results: [],
        value: '',
        source: [],
        products: [],
        title:'',
        desc:'',
        img: '',
        price: '',
        temp:''
    }

I just want to filter the array object products with value.

suppose below is my product object state

{"foodProductsId":4001,"subCategoryId":3024,"productName":"Angus Beef(500 gms)","brand":"Angus","price":240.0,"rating":4.5,"imageUrl":"https://cdn.pixabay.com/photo/2018/02/08/15/02/meat-3139641_960_720.jpg","quantity":118,"description":" Angus beef is beef taken from an Angus cow. Angus is a breed of cattle with its own unique characteristics. Angus cattle are known for having genes that make its meat more tender, marbled, and flavorful than regular beef. The Certified Angus Beef  brand is the best Angus brand available. It's a cut above USDA Prime, Choice and Select. Ten quality standards  including abundant marbling, ensure every bite is exceptionally flavorful, incredibly tender and naturally juicy."},{"foodProductsId":4002,"subCategoryId":3024,"productName":"Strauss Veal(250 gms)","brand":"Strauss","price":300.0,"rating":4.3,"imageUrl":"https://cdn.pixabay.com/photo/2018/04/12/11/43/veal-chop-3313222_960_720.jpg","quantity":111,"description":"Strauss veal: Our calves are never tethered and raised on a diet containing more iron, which is essential for developing a healthy immune system. Freedom of movement promotes good health and reduces stress, which helps to ensures tenderness. It's good for the calves and good for you."}

I just want to get the foodProductId based on product name.

eg: value= Angus Beef(500 gms) i supposed to get the id:4001

please help me regarding this query.

Thanks in advance

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
Thomas James
  • 187
  • 2
  • 16

1 Answers1

0

You can use Array.find(), to find the object based on value. Array.find() will return the first matching object from array, then you can get ID from that object,

//This will find the item from products array based on value
let selectedProduct = this.state.products.find(p => p.productName === this.state.value)

//Here you will get the Id
this.setState({
    selectedProductID: selectedProduct.foodProductsId
})

Demo

Note: I have stored foodProductsId in a state variable selectedProductID. It's completely up to you, how you want to use that object. If you want you re-render the component and display selected foodProductsId then you must go for state.

ravibagul91
  • 20,072
  • 5
  • 36
  • 59