0

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.

1
  • This is not valid. You can't have key: value in an array, only an object. Commented Oct 5, 2022 at 15:21

1 Answer 1

1

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