0

Say I have a list of medical objects, where I want to select all objects that have a category of "MEDICATION" and also have a "Trait", which is an array of Objects, for specifically the term "NEGATION". For example:

[ 
  { 
   Score: 0.9978850483894348,
   Text: 'prozac',
   Category: 'MEDICATION',
   Type: 'BRAND_NAME',
   Traits: [
    { 
      Name: "SIGN"
    },
    { 
      Name: "NEGATION"
    }
  ] 
},
{ 
  Text: "pulmonary embolism",
  Category: "MEDICAL_CONDITION",
  Type: "DX_NAME",
  Traits: [
   {
     Name: "DIAGNOSIS",
     Score: 0.9635574817657471
    } ]

Normally for a filter I could select all objects that are medications quite easily with:

Object.filter( obj => obj.Category === "MEDICATION" )

But how would I select all objects with Medication, and also Trait with object where Name === NEGATION?

The nested array throws me off.

Thank you!

1 Answer 1

3

You can still use a filter but use some on the sub array

Object.filter(obj => obj.Traits.some(t => t.Name === 'NEGATION'));

const values = [
  {
    Score: 0.9978850483894348,
    Text: 'prozac',
    Category: 'MEDICATION',
    Type: 'BRAND_NAME',
    Traits: [
      {
        Name: 'SIGN'
      },
      {
        Name: 'NEGATION'
      }
    ]
  },
  {
    Text: 'pulmonary embolism',
    Category: 'MEDICAL_CONDITION',
    Type: 'DX_NAME',
    Traits: [
      {
        Name: 'DIAGNOSIS',
        Score: 0.9635574817657471
      }
    ]
  }
].filter(obj => obj.Category === 'MEDICATION' && obj.Traits.some(t => t.Name === 'NEGATION'));

console.log(values);

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

2 Comments

Using some instead of find is probably more semantically correct
Changed to use some instead of find

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.