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.

11 thoughts on “Find Object Inside Array of Object Array”

  1. You could do that in one line. As I saw in your nested loop solution, you find in each object’s data, so first you could flatten the data in to array of objects and then find through that array

    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",
          },
        ],
      },
    ];
    
    const myId = 4;
    
    const res = items.flatMap((item) => item.data).find(({ id }) => id === myId);
    
    console.log(res);
    Reply

Leave a Comment