'Nested get request with map method

I have an api that returns an array of objects. I also have a second api that's dependent on the first api such that it needs to match a userID from the array of objects and fetch an object with detailed information. I am able to fetch my data from the first api however I am unable to generate an array of objects of detailed information for the second api, or push the objects retrieved from my second api into the first array.

So for example my first api returns an array of objects like the following response:

var return_greens = [{  
    ...,
    color: "green",
    userID: 123
  },
  { ...,
    color: "green",
    userID: 456
}]

My second api would require a userID and return a response object :

var detailed_info = {
   userID: 456,
   color: "green"
   day: "Monday",
   time: "1:00p",
   ...
}

Below is a sample code. I am using fetch() method however I am open to other methods or if there is a better way of writing the request.

const fetch_array_api = "";
const fetch_object_with_details_api = "";

fetch(fetch_array_api, { method: 'get' })
.then(response => response.json())
.then(data => {
   var return_greens = data.response;
   var data = return_greens.map((item, index) => {
        item.detailed_info = fetch(fetch_object_with_details_api + item.userID, { method: 'get' })
   })
   return data
})
.then(response => response.json())
.then(dataDetails => {
   console.log(dataDetails)
})
.catch(err => {
    console.error('Request failed', err)
})

I think I am having some trouble with the map() portion of this code. My understanding of promises and on using map() to iterate through the array of return_green and pushing the returned detailed_info object into the array may not be correct here. Would appreciate some help here. Ultimately I want to return an array of objects with detailed information within each object in the array. A little extra information: this bit of code will be dropped inside react's componentDidMount() method.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source