Find Object Inside Array of Object Array

I currently have an array of objects with each containing an array of objects. My goal is to find a nested object in a single line of javascript code. I am trying to avoid a nested loop, I know how to solve it that way but javascript offers a lot of elegant solutions for such scenarios. This is how my data looks like:

const items = [
    {
        id: 1,
        title: 'Test 1',
        data: [
            {
                id: 3,
                title: 'Test 3',
            },
            {
                id: 4,
                title: 'Test 4',
            },
        ],
    },
    {
        id: 2,
        title: 'Test 2',
        data: [
            {
                id: 5,
                title: 'Test 5',
            },
        ],
    },
];

With a nested loop:

let item = null;
for (let i = 0; i<items.length; i++) {
    for (let j = 0; j<items[i].data; j++) {
        if (items[i].data[j].id == myId) {
            item = items[i].data[j];
            return;
        }
    }
}

I feel like there is a more simplistic and prettier solution than this.

Leave a Comment