Traversing through an array within a Fetch request

My JSON object looks like this:

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

I have implemented a Fetch API in this way:

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

    })

Currently, it displays both following users in the same button like this:

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

I want to modify the Fetch call to show each following user in a separate button. Similar to this:

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

Answer №1

To iterate over the array and display each following profile, another loop is necessary:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting the size of Bootstrap alerts while ensuring the close icon remains correctly positioned

Below is the HTML code snippet I am working with: <div class="row mt-2"> <div class="col-lg-5"> <div id="alertmessages"></div> </div> <div class="col-lg-7"> <div class="btn-group-sm"> ...

Utilizing interactions between a JavaScript scrollable container and Python/selenium

My goal is to utilize Selenium/Python in order to automate the process of downloading datasets from . While I am new to Javascript, I am determined to learn and overcome any obstacles that may arise during this project. Currently, I am focusing on the init ...

Having trouble with gapi.client.request() not functioning properly?

I've been trying to use the Google API for freebase, and even though I'm following the correct call as per the documentation, it seems like there is an issue. The Chrome debugger is showing that something is wrong with this supposedly simple call ...

Fetch JSON information from various servers/domains through ajax requests

I am attempting to retrieve JSON data from a different server/domain. My expectation is that the code below should trigger a success alert, but instead, I am getting an error alert $.ajax({ url: "http://xxxx.com/zzzz", ...

creating divs inside a parent div with varying heights and using auto margins

Can anyone help me with this code snippet? <div style="position: relative;"> /***main***/ <div style="top:0"> /*****Content1****/ </div> <div> /*****Content2****/ </div> <div> ...

Retrieve both the key and value from an array of objects

I have been scouring the internet for a solution to this question, but I haven't come across anything that fits my needs. Let's say we have an array of objects like this -- "points":[{"pt":"Point-1","value":"Java, j2ee developer"},{"pt":"Point ...

The variable "$" cannot be found within the current context - encountering TypeScript and jQuery within a module

Whenever I attempt to utilize jQuery within a class or module, I encounter an error: /// <reference path="../jquery.d.ts" /> element: jQuery; // all is good elementou: $; // all is fine class buggers{ private element: jQuery; // The nam ...

Displaying a hand cursor on a bar chart when hovered over in c3.js

When using pie charts in c3js, a hand cursor (pointer) is displayed by default when hovering over a pie slice. I am looking to achieve the same behavior for each bar in a bar chart. How can this be done? I attempted the CSS below, but it resulted in the h ...

Building a multi-form application with HTML5 validation and Vue.js

I am working on a vue.js form that consists of multiple steps and requires HTML5 validation to be simplified. Here is a snippet of the code: <template> <div> <div v-if="activeForm === 1"> <h2> ...

Structuring Server Side Code with Node.js and Express

I am faced with the task of restructuring my server and its components. My goal is to streamline the process by segregating different functionalities. app.post("/login", function(request, response) { }); app.post("/register", function(request, response) ...

Problem with Jquery show/hide feature only resolved after refreshing the page

I built a checkout page that consists of three fieldsets with unique IDs - 1, 2, and 3. I want the page to initially display only fieldset 1 while hiding fieldsets 2 and 3. Here is the jQuery code I used: $(document).ready(function(){ $("#1").show(); ...

Feature exclusively displays malfunctioning image URLs for the web browser

Hello everyone! I've been diving into learning JavaScript and recently attempted to create a function that randomly selects an image from an array and displays it on the browser. Unfortunately, despite my efforts, all I see are broken link images. Her ...

When I try to post using the raw feature in Postman in Node.js, the post ends up empty

My API is supposed to receive data for saving in the database. However, when I call the PUT method, my req.body.nome returns empty. It works fine with form-urlencoded, but I've tried using body-parser and it's deprecated. Here is my request usin ...

Exploring the use of ngResource in conjunction with HttpBackend - Potentially unreached rejection issue

Issue Currently, I am working on testing a controller utilizing Karma, Mocha, Chai, and PhantomJS as part of the testing process. IndexCtrl.js (simplified) app.controller('IndexCtrl', ['$scope', '$resource', function($scope ...

Utilize Meteor's ability to import async functions for seamless integration into method calls

Encountering an issue with this Meteor app where the error TypeError: vinXXX is not a function occurs when attempting to call an exported async function named "vinXXX" from within a method call in a sibling folder, which has been imported in the methods f ...

How to utilize jQuery to extract a portion of a lengthy string delimited by specific

I have a single string let input = "T-shirt SKU-TST071815-BLACKTHAMB (Code: 111R)" I need the following output let output = "TST071815-BLACKTHAMB" "T-shirt SKU-TST071815-BLACKTHAMB (Code: 111R)" is constantly generated by the database and changes eve ...

The render() method of the component is failing to execute even after the mobx store value has been updated

After successfully updating the store before fetching data from the server, everything seems to be working fine. However, once the data is fetched and the store is updated again, the render() method does not get called. Check out this code snippet @acti ...

Encountering issues with link functionality on homepage due to React-Router v6 and Material-UI Tab integration

I'm currently working on a homepage that requires different page links. Below you can find the necessary code snippet for setting up the tabs and routes for each page: <li> The tabs are located here - <Link to="/demo">D ...

How can I restrict the draggable space? It is only working on the top and left sides, but I want to disable it on the right and bottom

Attempting to prevent the draggable items from overflowing beyond the body. Succeeded in limiting movement on the top and left sides. Encountering difficulty restricting motion on the right side and bottom. e.pageX -= e.offsetX; e.pageY -= e.offsetY; ...

Learn how to establish a state using an array and effectively utilize the setState() method in React

For my latest project, which is API based, I am working with arrays that contain sub-arrays. How can I define a state with an array and utilize the setState() method to work with the entire array? ...