Home > Software design >  How to filter one element of JSON array when specific value exist in it
How to filter one element of JSON array when specific value exist in it

Time:04-04

I have const allAlertsData which is JSON array with elements as objects. I want to filter specific element of array once it's property trainId === idTrain. const idTrain is taken from useParams. enter image description here

So out of whole allAlertsData, I want to filter out only element[0] if idTrain will be TLK-12345.

Can You please suggest how to filter only one element of JSON array based on matching it's specific property ?

CodePudding user response:

You can use the find() method of an Array:

const foundAlert = allAlertsData.find(alert => alert.trainId === trainId)

The find method will return the first element where the provided testing function evaluates truthy. (source)

  • Related