[FIXED] Filter parent object based on child object containing value

Issue

I have an object, benefitGroups that contains benefits. Each item in benefits contain an array of coverageLineIds. How can I filter the benefitGroups object to only contain benefits that include ID 1 in the coverageLineIds array?

const benefitGroups=  [
     {
      id: 1,
      name: "Benefit Group A",
      benefits: {
         id: 1,
         benefitGroupId: 1,
         name: "Benefit Z",
         coverageLineIds: [1, 2]
      },
      {
         id: 2,
         benefitGroupId: 1,
         name: "Benefit X",
         coverageLineIds: [1, 2]
      },
      {
         id: 3,
         benefitGroupId: 1,
         name: "Benefit Y",
         coverageLineIds: [1, 2]
      },
    },
     {
      id: 2,
      name: "Benefit Group B",
      benefits: {
         id: 4,
         benefitGroupId: 2,
         name: "Benefit I",
         coverageLineIds: [1]
      },
      {
         id: 5,
         benefitGroupId: 2,
         name: "Benefit J",
         coverageLineIds: [1]
      },
      {
         id: 6,
         benefitGroupId: 2,
         name: "Benefit H",
         coverageLineIds: [1]
      },
    },
     {
      id: 3
      name: "Benefit Group C",
      benefits: {
         id: 7,
         benefitGroupId: 3,
         name: "Benefit D",
         coverageLineIds: [3, 4]
      },
      {
         id: 8,
         benefitGroupId: 3,
         name: "Benefit E",
         coverageLineIds: [3, 4]
      },
      {
         id: 9,
         benefitGroupId: 3,
         name: "Benefit F",
         coverageLineIds: [3, 4]
      },
    },
]

In the above example, I would want to return Benefit Group A and B as their benefits contain coverage line IDs of 1.

Solution

First of all, your JSON is invalid. Your benefits should be in array.

Once, fixed here is what you’re looking for:


const id = 1;

const result = benefitGroups.filter((group) => {
  return group.benefits.some((benefit) => benefit.coverageLineIds.includes(id));
});

Answered By – khaiyom

Answer Checked By – Pedro (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published