0

Given the following array of objects, I'm trying to work out how to filter the top array based on the Event array having an object containing an ID of 30

var staff = [];
staff.push({
    Id: 122,
    Events: [
        {Id: 30,Name: "Foo"},
        {Id: 57,Name: "Bar"}
    ]});
staff.push({
    Id: 122,
    Events: [
        {Id: 57,Name: "Bar"}
    ]});
    

So far I've tried variations of the following:

$.grep(staff, function (item) {
    return item.Events.Id == 30
});

Any help would be greatly appreciated

Expected output:

var staff = [{Id: 122, Events: [{Id: 30,Name: "Foo"},{Id: 57,Name: "Bar"}]}];

1 Answer 1

1

var staff = [];
staff.push({
  Id: 122,
  Events: [
    { Id: 30, Name: 'Foo' },
    { Id: 57, Name: 'Bar' }
  ]
});
staff.push({
  Id: 122,
  Events: [{ Id: 57, Name: 'Bar' }]
});

const res = staff.filter((item) => item.Events.some((e) => e.Id === 30));
console.log(res);

Sign up to request clarification or add additional context in comments.

2 Comments

perfect thanks, makes sense needed to filter the inner object the same as the outer
staff.filter(item => item.Events.some(e => e.Id === 30)) would be a lot better here, as it would return early if a match is found.

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.