问题描述
我有一个从ajax调用返回的数组,其中将包含用户列表。我需要为列表中的每个用户名进行ajax调用以获取数据。我已经编写了所需的代码,并且能够访问服务器并获得列表中每个用户的响应。提供响应后,我想创建一个数组或一个对象,该数组或对象将保存用户名和个人资料图像url,以便稍后在前端使用它。我面临的问题是,只有一个用户将被添加到对象中,我该如何解决呢?
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将位于foreach循环下,对于用户的列表/数组,您可以在函数顶部声明一个userInfo数组,并在提取数据时将其推入该函数。 ..我对您的代码做了一些修改,请检查一下。
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)
}