Home > database >  Filter a Nested value inside and an Object
Filter a Nested value inside and an Object

Time:11-28

Given the following objects stored in documents array:

[
    {
        "id": 61,
        "created_at": "2022-11-02T15:36:25 00:00",
        "updated_at": "2022-11-02T15:36:25 00:00",
        "translations": [
            {
                "field": "name",
                "lang": "it",
                "text": "IT_Codice di Condotta_NEW"
            },
            {
                "field": "name",
                "lang": "en",
                "text": "EN_Code of Conduct_NEW"
            },
            {
                "field": "pdf_url",
                "lang": "en",
                "text": "/var/www/vhosts/marchettopellami.com/reservedarea.marchettopellami.com/docs/docs/en/a-20221125081444740491.pdf"
            },
            {
                "field": "pdf_url",
                "lang": "it",
                "text": "/var/www/vhosts/marchettopellami.com/reservedarea.marchettopellami.com/docs/docs/it/draft-20221127194030220505.pdf"
            }
        ]
    },
    {
        "id": 63,
        "created_at": "2022-11-02T15:38:40 00:00",
        "updated_at": "2022-11-02T15:38:40 00:00",
        "translations": [
            {
                "field": "name",
                "lang": "it",
                "text": "IT_NEW"
            },
            {
                "field": "name",
                "lang": "en",
                "text": "EN_NEW"
            },
            {
                "field": "pdf_url",
                "lang": "en",
                "text": "TheFerrari-GlobalMarketingStrategy-20221124133159490323.pdf"
            },
            {
                "field": "pdf_url",
                "lang": "it",
                "text": "20221124160623761884.pdf"
            }
        ]
    },
    
]
 

My goal is to filter the value of "text" nested inside "translations" where "field" have value of "name". In other words filter IT_Codice di Condotta_NEW or EN_Code of Conduct_NEW for example

const resultsArray = documents.filter((d) => {
                       return Object.values(d)
                       .join(" ").toLowerCase()
                       .includes(e.target.value.toLowerCase())
                     });  

At the moment the filter is working with "id", "created_at", "updated_at". I assume I should map translations array, but at the moment i can not even access "translations". Thanks for your help.

CodePudding user response:

You could expand those translation arrays by chaining the following after Object.values(d):

    .flatMap(val => Array.isArray(val) ? val.map(({text}) => text) : val) 

So it becomes:

const resultsArray = documents.filter((d) => {
    return Object.values(d)
        .flatMap(val => Array.isArray(val) ? val.map(({text}) => text) : val) 
        .join(" ").toLowerCase()
        .includes(e.target.value.toLowerCase());
});
  • Related