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 an nested Object with filter and map with JavaScript

I know that this is close to a duplicate but I can’t get the code to work. I have an object that I need to filter and I’m currently trying to emulate the accepted as an answer the code at Javascript filtering nested arrays

My data object is:

[{
    "project_num": "5R01DA012513-23",
    "principal_investigators": [{
      "profile_id": 2076451,
      "full_name": "PK",
      "title": ""
    }]
  },
  {
    "project_num": "5R01DK118529-03",
    "principal_investigators": [{
      "profile_id": 8590844,
      "full_name": "HW",
      "title": "PROFESSOR, SCIENTIFIC DIRECTOR"
    }]
  },
  {
    "project_num": "3R01AA025365-05S1",
    "principal_investigators": [{
      "profile_id": 8730036,
      "full_name": "JJ",
      "title": "ASSOCIATE PROFESSOR OF PSYCHIATRY"
    }]
  },
  {
    "project_num": "1R01HL163963-01",
    "principal_investigators": [{
        "profile_id": 2084037,

        "full_name": "KH",
        "title": "ASSOCIATE PROFESSOR"
      },
      {
        "profile_id": 11309656,
        "full_name": "AM",
        "title": "RESEARCH ASSISTANT PROFESSOR"
      }
    ]
  },
  {
    "project_num": "5R25HL092611-15",
    "principal_investigators": [{
      "profile_id": 1886512,
      "full_name": "CW",
      "title": "P"
    }]
  }
]

and my JavaScript code is:

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

let payLoad = 1886512
const result = this.reporterData.map(t => {
  const principal_investigators = t.principal_investigators.filter(d =>
    d.profile_id === payLoad);
  return { ...t,
    principal_investigators
  };
})

I need to pass in a profile_id as a payload and return the objects that will fill a data table.

The data can be 1000’s of items and the principla_investigators can be multiple entries. When I use the code that I have it return all of the objects. Can someone point out my error? Thanks

>Solution :

You can try doing like this:

const result = this.reporterData.filter((t) => {
  const principal_investigators = t.principal_investigators.filter((d) => d.profile_id === payLoad)
  return (principal_investigators.length > 0)
})
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