0

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 ?

2
  • Do you know Array.filter? Commented Apr 3, 2022 at 21:17
  • @Manfred whilst the filter method will return the desired element, it will return it as an Array. The question specifically wanted to filter out only one element. Commented Apr 3, 2022 at 21:33

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.