Skip to content

How to check if array of objects that contains another array of object has property

Hi I have an array of objects which contains another array of objects. I need to find an object in array which contains another object in it’s array with certain propery ID. Let’s say i need to find an object in casses array which contains a user with certain ID. ID for user is unique.

  casses = [
       {
        caseName: 'case 1',
        date: '2021-05-4',
        id: '123',
        user: [{name: 'Vlad', id: '1'}, {name: 'Misha', id: '2'}]
       },
       {
        caseName: 'case 2',
        date: '2021-05-4',
        id: '123',
        user: [{name: 'Alina', id: '3'}, {name: 'Alex', id: '4'}]
       },
       {
        caseName: 'case 3',
        date: '2021-05-4',
        id: '123',
        user: []
       },
    ]

I could use a nested loops and so on. But i wondering is it possible to do with one line ? Something like this but one level deeper:

let val = casses(item => item.id === element.id); ‚Äč

Answer

Assume your case with ID set to “3”

Try below

const ID = "3";

const casses = [
    {
        caseName: "case 1",
        date: "2021-05-4",
        id: "123",
        user: [
            { name: "Vlad", id: "1" },
            { name: "Misha", id: "2" }
        ]
    },
    {
        caseName: "case 2",
        date: "2021-05-4",
        id: "123",
        user: [
            { name: "Alina", id: "3" },
            { name: "Alex", id: "4" }
        ]
    },
    {
        caseName: "case 3",
        date: "2021-05-4",
        id: "123",
        user: []
    }
];

casses.find(item => item.user.some(subItem => subItem.id === ID));