Home > Software engineering >  JS Object - Filter for a specific field
JS Object - Filter for a specific field

Time:12-08

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

{
    "id": 118,
    "name": "MIXY",
    "thumbnail": null,
    "translations": [
        {
            "field": "name",
            "lang": "it",
            "text": "MIXY"
        },
        {
            "field": "name",
            "lang": "en",
            "text": "MIXY"
        },
        {
            "field": "thumbnail",
            "lang": "en",
            "text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypng.png"
        },
        {
            "field": "pdf_url",
            "lang": "en",
            "text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypdf.pdf"
        }
    ]
},
{
    "id": 119,
    "name": "CITY",
    "thumbnail": null,
    "translations": [
        {
            "field": "pdf_url",
            "lang": "en",
            "text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypdf.pdf"
        },
        {
            "field": "name",
            "lang": "it",
            "text": "CITY"
        },
        {
            "field": "thumbnail",
            "lang": "en",
            "text": "/var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypng.png"
        },

        {
            "field": "name",
            "lang": "en",
            "text": "CITY"
        },
    

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

cardObject?.['translations']?.[2]?.['text'] 

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

card?.['translations'].hasOwnProperty('pdf_url')

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

CodePudding user response:

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

const pdfUrl = cardObject.translations.find(translation => translation.field === 'pdf_url');
console.log(pdfUrl.text);
// /var/www/vhosts/mysite.com/reservedarea.mysite.com/docs/color_cards/en/mypdf.pdf
  • Related