2

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); ​
2
  • 1
    Nested loops is a good idea. You can usually then replace loops with builtin functions, that take over the looping, e.g. Array.prototype.find or Array.prototype.some, but accordingly, you'll need nested ones: casses.find(outerObject => outerObject.user.some(user => user.id === '1')); Commented Nov 15, 2021 at 14:00
  • I would like to use loops myself, they are much easy to read and understand. But my task was to do it in very few lines of code. Commented Nov 15, 2021 at 14:20

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

4 Comments

@Vlad, check this out!!
Thank you so much for a great answer), it helped me a lot!
If not using build in function, how can I quickly locate it? If using for loop I have to go over all then it is not inefficient.
using built-in functions is cleaner than using for loops and they are already efficient as some and find method stops looping after finding the first match. You will have to add that logic within loops as well.

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.