Skip to content
Advertisement

JS Object – Filter for a specific field

In order to check from my frontend application if there is or not a PDF I want to search into my nested object ‘translations’ for the field named “pdf_url”.

JavaScript

The problem I am dealing with i that for every cardObject (id: 118, 119) the pdf_url can be in position 0, 1, 2, 3 or n inside that the translations array. So when I try to access it like this, for example

JavaScript

I am not always sure I check the “pdf_url” of my card. I would firstly check is the object has “pdf_url” key value using

JavaScript

and then? Should I loop over the translations array of objects? Is there a simple way to “reduce” or even better group my data?

Advertisement

Answer

You can use Array.prototype.find to find the first object in the array that has a field property with the value pdf_url.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement