Home > Software engineering >  Extract element value out of array of objects
Extract element value out of array of objects

Time:10-08

I have an array of objects where I have to find the segmentId of "PUBLICATIONS_OVERVIEW".

"sections": [
0: {
    "title": "CAMPAIGNS",
    "segments": [
        {
            "title": "CAMPAIGN_DA",
            "segmentId": 145
        },
        {
            "title": "CAMPAIGN_IM",
            "segmentId": 146
        },
        {
            "title": "CAMPAIGN_ENG",
            "segmentId": 147
        },
        {
            "title": "CAMPAIGN_DEMO",
            "segmentId": 148
            ]
        },
        {
            "title": "CAMPAIGN_BUDGET",
            "segmentId": 149
                }
            ]
        }
    ]
},
1: {
    "title": "PUBLICATIONS",
    "segments": [
        {
            "title": "PUBLICATIONS_OVERVIEW",
            "segmentId": 150
        },
        {
            "title": "PUBLICATIONS_POSTS",
            "segmentId": 151
        }
    ]
}
]

The code that I have works just fine, but I would like to merge it into one line of code and I can't seem to be able to do it (output is always undefined).

const publicationSegments = this.sections.find(section => section.title === 'PUBLICATIONS');
const segmentId = publicationSegments.segments.find(segment => segment.title === 'PUBLICATIONS_OVERVIEW').segmentId;

I would like to know how it is done properly in one single line of code.

CodePudding user response:

Just replace publicationSegments with the expression you used to initialize it.

const segmentId = this.sections.find(section => section.title === 'PUBLICATIONS').segments.find(segment => segment.title === 'PUBLICATIONS_OVERVIEW').segmentId;
  • Related