微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在ajax调用之后将多个键值对添加到对象

如何解决在ajax调用之后将多个键值对添加到对象

我有一个从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)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。