How to pick out specific data within complex objects using JS

Viewed 47

So I'm working with a super neat API that gives medication interactions. It gives me the following object:

https://rxnav.nlm.nih.gov/REST/interaction/list.json?rxcuis=84815+82110+114228

I've been trying to come up with a function to grab all of the interaction descriptions with no avail. The following is my best attempt (returned is the object):

for (var i = 0; i < returned.fullInteractionTypeGroup[0].fullInteractionType.length; i++) {
  for (var j = 0; j < returned.fullInteractionTypeGroup[0].fullInteractionType[i].length; j++) {
    console.log(returned.fullInteractionTypeGroup[0].fullInteractionType[i].interactionPair[j].description);
  }
}

This solution only gives me the first interaction pair for some reason. Am I looping wrong? Is there an easier way to do this? My head hurts.

2 Answers

This should work:

for (let x of returned.fullInteractionTypeGroup[0].fullInteractionType) {
  for (let y of x.interactionPair) {
    console.log(y.description);
  }
}

This code handles everything for you, from fetching the data, to listing all the descriptions, to even filtering out duplicate descriptions.

fetch('https://rxnav.nlm.nih.gov/REST/interaction/list.json?rxcuis=84815+82110+114228')
  .then(response => response.json())
  .then(returned => {
    const descriptions = returned.fullInteractionTypeGroup[0].fullInteractionType.reduce((descriptions, { interactionPair }, i, arr) => {
      interactionPair.forEach(({ description }) => descriptions.add(description));
      if (i == arr.length - 1) return [...descriptions];
      return descriptions;
    }, new Set());
    console.log(descriptions);
  });

Related