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

在Fetch调用中遍历数组

如何解决在Fetch调用中遍历数组

我有一个像这样的JSON对象:

[{"user": "poetry2","following": ["Moderator","shopaholic3000"]}]

我正在使用这样的Fetch API:

    fetch (`/profile/${username}/following`)
    .then(response => response.json())
    .then(profiles => {
        profiles.forEach(function(profile){
            profiledisplay = document.createElement('button');
            profiledisplay.className = "list-group-item list-group-item-action";
            profiledisplay.innerHTML = `
            ${profile.following}`;
            listFollowing.appendChild(profiledisplay);
        })

    })

现在,它在如下所示的同一按钮中显示以下两个用户

<button class="list-group-item list-group-item-action">
            Moderator,shopaholic3000</button>

如何修改Fetch调用以在单独的按钮中显示以下每个用户。像这样:

<button class="list-group-item list-group-item-action">
            Moderator</button>
<button class="list-group-item list-group-item-action">
            shopaholic3000</button>

解决方法

因此,您需要执行第二个循环以遍历下面的数组

profiles.forEach(function(profile){
  profile.following.forEach(name => {
    const profileDisplay = document.createElement('button');
    profileDisplay.innerHTML = `${name}`;
    ....
  });
});

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