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.
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)