Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter parent object based on child object containing value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
});

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading