在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}`;
    ....
  });
});