简体   繁体   中英

add multiple key value pairs to an object after ajax call

I have an array that is returned from an ajax call and will contain a list of users. I need to make an ajax call for each username that is in the list to fetch the data. I've writed the needed code and I'm able to hit the server and get the respponse for each user in the list. After the response is provided I want to create an array or an object that will hold the username and the profile image url to use it later on the frontend. I'm facing the problem that only one user will be added to the object, how I can fix this?

    fetchFeatured(){
      axios.get('https://www.example.com/directory/profiles/all')
        .then( (response) => {
          const profiles = JSON.parse(response.data.profile_data.profile_list)
          profiles.length = 6
          const featured = {}
          profiles.forEach( (profile) => {
            axios.get('https://www.example.com/'+profile+'/')
              .then( (response) => {
                featured.username = profile
                featured.profile_img_url = response.data.users.profile_pic_url_hd
              })
          })
        })
        console.log(featured)
    }

featured will be under the foreach loop and for user's list/array you can declare an userInfo array top of the function and push featured into it when data is fetched. .. I slightly modified your code please check it out.

fetchFeatured(){
let userInfos=[];
  axios.get('https://www.example.com/directory/profiles/all')
    .then( (response) => {
      const profiles = JSON.parse(response.data.profile_data.profile_list)
      profiles.length = 6          
      profiles.forEach( (profile) => {
        axios.get('https://www.example.com/'+profile+'/')
          .then( (response) => {
            let featured = {};
            featured.username = profile;
            featured.profile_img_url = response.data.users.profile_pic_url_hd;
            userInfos.push(featured);
          })
      })
    })
    console.log(featured)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM