0

I searched on this site and read several articles about reduce, map, and filter, but I think I just don't know what to search for. I'm running several queries on an API, where first I run search #1 for XYZ, then with the results from Search #1, I run Search #2 with one of the properties from the array of results that Search #1 gets. Basically it goes down a chain of promises, getting more details from the API as it goes. I can make it work with a cheat / workaround but it feels there must be a more ES6 succinct way to do this.

async function LoopOverArrayAndRunSearch(json) {

   for await (let item of json) {
      searchNumber1(item.property1).then(data => {

     // Find the items where the search name matches the result name
     let nameMatchExactlyArray = data.filter(apiItem => apiItem.name === item.property1);

    // get the id from the first value of the array

    console.log(nameMatchExactlyArray[0].id);    // this feels sloppy!
    let matchingID = nameMatchExactlyArray[0].id;

    // run search2 using the matchingID
    searchNumber2(matchingID).then ....


 }    
}
Kyle Pennell
  • 5,747
  • 4
  • 52
  • 75
  • @HereticMonkey Could be a dupe but could also someone else who doesn't know what to search – Kyle Pennell Aug 30 '19 at 14:41
  • 2
    That's the point of duplicates. If someone finds your question (by a search that matches your key words and phrases), they get a link to the duplicate, and the answer, without having the answer duplicated in a million places. – Heretic Monkey Aug 30 '19 at 14:43

1 Answers1

1

Use .find instead of .filter:

let foundId = (data.find(apiItem => apiItem.name === item.property1)).id;
volcanic
  • 312
  • 1
  • 6