Navigating JSON Data with ES6 Iteration

Issue Description

There are two APIs I am working with. The first one, let's call it API #1, provides JSON data related to forum posts as shown below:

[{
    "userId": 1,
    "id": 10,
    "title": "Tt1",
    "body": "qBb2"
  },
  {
    "userId": 2,
    "id": 11,
    "title": "TT4",
    "body": "BBB5"
  }]

The second API, referred to as API #2, contains personal information such as names and user IDs.

[
  {
    "id": 1,
    "name": "Lera",
    "username": "Lera2",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ebae86abc5888486">[email protected]</a>",
    "address": {
      "street": "GGa",
      "suite": "Ap3. 333",
      "city": "Gwee",
      "zipcode": "2222-3333",
      "geo": {
        "lat": "-11213",
        "lng": "312424"
      }]

I aim to extract unique names from API #2 and place each name within a div labeled "User". Subsequently, I plan to display the posts from API #1 under the corresponding User div based on a matching field ("id").

Progress Made So Far

fetch('API-#2')
.then(function(response) {
    return response.json();
    })
.then(function(myJson) {
    document.getElementById("testDiv").innerHTML = JSON.stringify(myJson);
});

The current output displays raw data from API #2 without any processing.

Challenges Faced

  1. I need to utilize methods like map, reduce, or similar to iterate through names in API #2 and create respective User divs.
  2. It is necessary to loop through posts in API #1 and assign each post under the appropriate User div by matching their 'id' fields.

UPDATE

fetch('API-#2')
.then(function(response) {
    return response.json();
    })
.then(function(myJson) {
    myJson.filter(function (item, index, self) { return self.indexOf(item) === index; }).forEach(function (user) { 
      document.getElementById("testDiv2").innerHTML += "<div>" + user.name + "</div>"; 
    });
});

The above code snippet successfully lists out the unique names fetched:

Name 1
Name 2
Name 3

My next step involves associating the posts with the corresponding names using their IDs for cross-referencing.

Answer №1

If you're looking for a starting point, consider the following example:

fetch('API-#2')
.then((response) => {
    return response.json();
    })
.then((myJson) => {
    let uniqueValues = myJson.filter((item, index, self) => { 
        return self.indexOf(item) === index; 
    });
    
    uniqueValues.forEach((user) => { 
      document.getElementById("testDiv").innerHTML += "<div>" + user.name + "</div>"; 
    });
});

Interact with myJson like any other JavaScript object. You have the option to filter out duplicate values and loop through the array of data.

Consider utilizing jQuery or another library for a more efficient way to generate HTML without string concatenation – this code serves as an example.

Answer №2

I'm not sure if this meets your needs.

This example assumes that you have already fetched the data from API1 and API2.

In order to streamline the process, I transform the user Array into a user Object. The keys of the Object represent the userid, while the values are the original data.

This arrangement facilitates quicker user lookups based on the topic:

    let user = userList[topic.userId];

Next, there is a loop that converts the Topic Array from an object structure to an array of strings. These strings are then concatenated with '\n' as a separator.

The resulting string is inserted into the designated div intended for displaying the generated HTML.

// Assume that this data came from the first API call
let api1Resp = [
  {
    "userId": 1,
    "id": 10,
    "title": "Something Cool",
    "body": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  },
  {
    "userId": 2,
    "id": 11,
    "title": "Something else",
    "body": "Excepteur veniam deserunt eu fugiat occaecat voluptate Lorem fugiat officia proident laboris pariatur minim laboris qui. Reprehenderit veniam eu duis anim incididunt adipisicing dolor officia. Ad et magna sint sit sint nisi officia labore do deserunt ut velit quis tempor do nulla adipisicing. Sit aliqua incididunt fugiat aute ex mollit ea aliquip et magna ut id deserunt ut. Dolore ullamco qui sunt Lorem cillum aliquip exercitation. Irure cillum laboris sit eu tempor dolore proident consectetur irure laboris eiusmod reprehenderit."
  },
  {
    "userId": 2,
    "id": 12,
    "title": "Hot Stuff",
    "body": "Ullamco minim aute laboris enim veniam ex et. Do Lorem laborum veniam labore incididunt occaecat eiusmod et occaecat eiusmod non sunt non non. Ad eiusmod ipsum ex velit cupidatat consequat anim consectetur dolore ea veniam.\n"+
            "\n"+
            "Consequat commodo culpa ipsum mollit voluptate do in adipisicing ea quis id est duis labore aliqua nisi tempor. Reprehenderit reprehenderit veniam nostrud excepteur aliquip ut sit tempor consectetur excepteur. Minim fugiat aliqua laboris aliqua nostrud id ex proident. Dolore amet occaecat dolor deserunt tempor irure labore veniam ad culpa mollit ex irure laborum anim cillum laborum. Est sunt nisi anim quis elit anim in. Velit qui reprehenderit laboris et est adipisicing quis esse ullamco nisi anim. Voluptate velit commodo ex laboris consequat dolor culpa consequat cupidatat occaecat ullamco fugiat aliqua minim voluptate commodo proident. Aliquip laboris ad sint consequat eiusmod minim velit velit id.\n"+
            "\n"+
            "Culpa Lorem laboris elit non fugiat aute et labore exercitation et in sunt ullamco tempor irure non quis. Laborum nulla nostrud labore incididunt ipsum Lorem ut aliquip velit deserunt sunt exercitation aliqua irure proident laboris. Quis et velit anim in id enim culpa id. Ex consequat labore adipisicing sunt non in proident cupidatat esse officia nostrud. Pariatur dolor officia culpa deserunt aliqua id exercitation duis magna sunt in elit officia. Aliquip nulla veniam consectetur ut sit labore officia sit reprehenderit.\n"+
            "\n"+
            "Et est esse adipisicing veniam sint laborum Lorem elit. Culpa ad anim irure ut dolore fugiat dolor ullamco ea culpa aliqua eiusmod nulla. Adipisicing dolore incididunt non velit laborum mollit sit nulla. Nisi quis pariatur excepteur ullamco id eu laborum anim esse. Ut elit nisi exercitation anim elit consectetur velit officia laboris quis et. Occaecat consequat duis duis tempor ullamco dolor anim tempor non occaecat occaecat irure dolore."
  },
  {
    "userId": 2,
    "id": 13,
    "title": "This is a longer title",
    "body": "Excepteur veniam deserunt eu fugiat occaecat voluptate Lorem fugiat officia proident laboris pariatur minim laboris qui. Reprehenderit veniam eu duis anim incididunt adipisicing dolor officia. Ad et magna sint sit sint nisi officia labore do deserunt ut velit quis tempor do nulla adipisicing. Sit aliqua incididunt fugiat aute ex mollit ea aliquip et magna ut id deserunt ut. Dolore ullamco qui sunt Lorem cillum aliquip exercitation. Irure cillum laboris sit eu tempor dolore proident consectetur irure laboris eiusmod reprehenderit."
  }
];


// Assume that this data came from the second API call
let api2Resp = [
  {
    "id": 1,
    "name": "Lera",
    "username": "Lera2",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8edc5e886cbc7c5">[email protected]</a>",
    "address": {
      "street": "GGa",
      "suite": "Ap3. 333",
      "city": "Gwee",
      "zipcode": "2222-3333",
      "geo": {
        "lat": "-11213",
        "lng": "312424"
      }
    }
  },
  {
    "id": 2,
    "name": "John",
    "username": "Big John",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9aba389a5a0bdbda5acafa6a6bde7aaa6a4">[email protected]</a>",
    "address": {
      "street": "123 Street",
      "suite": "",
      "city": "Smallville",
      "zipcode": "12345-6789",
      "geo": {
        "lat": "-11213",
        "lng": "312424"
      }
    }
  }
];

// Transform the array into an object where the user id is the key and the user info object is the value.
// This simplifies data retrieval.
let userList = api2Resp.reduce(
  (newUserList, user) => {
    newUserList[user.id] = user;
    return newUserList;
  }, {}
);


// Generate all of the output
let html = api1Resp.map(
  topic => {
    // Try to retrieve the user info from the topic
    let user = userList[topic.userId];
    // If user is undefined it means it's not in the list

    return `
    <div class="topic" id="topic:${topic.id}">
      <h2>${topic.title}</h2>
      <div class="author">By: <a href="mailto:${user.email}">${user.username}</a></div>
      <div class="body">${topic.body.replace(/\n/g, '<br/>\n')}</div>
    </div>`;
  }
).join('\n');

let el = document.getElementById('output');
el.innerHTML = html;
<div id="output"></div>

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

What could be causing my jQuery handler to not capture my form submission?

I am developing a Ruby web application and using JQuery and AJAX to send/receive data. However, I am facing an issue where pressing the enter key does not submit the form. What should I do to ensure that my form submits successfully? Within my Foundation ...

Retrieve information using JSON.parse from an ajax request

I have been searching high and low for the solution. Here is the JSON string "[{"id":"0"}]" I attempted obj['id'] and obj.id but to no avail $.ajax({ url: 'php/checkdoctorappointmentonday.php', data: 'doc ...

`Automatic toggling between two inputs with adjustable settings`

There are 2 input fields in my code that only accept positive floats with 2 decimals. Any other characters entered should be automatically removed using the change() function. Whenever the value of one input is changed, the value of the other input should ...

Creating a user-friendly three step wizard on a single webpage using the dynamic duo of AJAX and PHP

I am facing a challenge while trying to set up a 3-step wizard on a single page using ajax. I have created two PHP files for Form2 and Form3 generation. While the first step of creating Form2 worked smoothly, I encountered an issue with the second step inv ...

jquery plugin causing issues with bootstrap button functionality

Currently, I am utilizing the jQuery form plug-in to post my form in an Ajax way. The post function is functioning perfectly with the default button. However, it seems to encounter issues when I try to use a custom Bootstrap button as shown below. Could so ...

Even after defining routes, Node Express continues to throw a 404 error

It appears that troubleshooting this issue may be challenging without providing more context. Here is the setup I have in a compact modular configuration: //index.js also known as the server ... // defining views path, template engine, and default layou ...

Establishing Node.js environment variables when invoking `npm run` command

package.json { "scripts": { "start": "NODE_ENV=development node ./index.js" } } If we wanted to pass and override NODE_ENV when running npm run start, is it possible? npm run start NODE_ENV=production ...

Should we be concerned about the ethics of running javascript that is fetched through an AJAX request?

Currently, I am working on updating an existing web application that allows for user administration and login capabilities. One of the features involves modifying a user's details through a dialog box, where the updated data is then sent to the server ...

What is the mechanism behind the setTimeout function as an asynchronous timer when we specify a specific duration?

Can you identify the coding instructor, possibly Net Ninja or Fireship, who explained that in asynchronous setTimeout, it promises to run after a minimum time of 1 second but may actually take longer (e.g. 1015 milliseconds or 1200 milliseconds)? What ha ...

Revoke the prior invocation of the Google Maps geocoding function

While working on implementing an autocomplete with JavaScript and the Google Maps geocode method (using the keyup event on input), I have encountered a problem where I sometimes receive the results of the previous search instead of the current one. I am l ...

What is the method for renaming Props in Vue components?

I recently embarked on my VueJS journey and attempted to implement v-model in a component, following an example I found. <template> <div class="date-picker"> Month: <input type="number" ref="monthPicker" :value="value.month" @in ...

Install the following packages using npm: tailwindcss, postcss, autoprefixer, error, and next

npm ERR! code ERESOLVE npm ERR! ERESOLVE could not find a solution to the problem npm ERR! npm ERR! While trying to resolve: [email protected] npm ERR! Found: [email protected] npm ERR! node_modules/react npm ERR! requires react@">=16.8 ...

A guide to accessing a specific worksheet on a Sharepoint Excel spreadsheet using Python

In my Python project, I am using the Office 365 REST Python Client library to access and read an excel workbook with multiple sheets. Although I have successfully authenticated, I am struggling to correctly append the sheet name to the file name in order ...

Guide to inserting literal newline and carriage return characters into a CSV file using DictWriter in Python

I am currently using Windows 10, Python 3.8.1 64-bit, and Visual Studio Code. My current project involves fetching data from an API using a POST request. The response data is in JSON format, which I save to a text file. This JSON data contains multiple ta ...

Modifying alignment of buttons in React components

Transforming the typical Tic Tac Toe game from the React tutorial, with an added one-player feature. Oddly, button alignment shifts out of place once a value is inserted; causing the button to drop by about 50px until the row is filled with values, after ...

Different Ways to Access an Array in an EJS Template

After receiving a list of IDs from an API, I need to include them in a URL within an EJS template to retrieve the correct items. For example, the URL format is: Here are some example IDs: 526 876 929 The desired output inside the EJS template: <li&g ...

Removing error messages upon form reset initiated by an API request

Is there a way to clear error messages that appear beneath a text field when resetting form fields with values from an api call? In my Formik form, I have three fields that are loaded from an api database call along with a Reset button that reloads these ...

Run a series of promises in an array one after the other without relying on async and await

Imagine having an array filled with promises. Each element in this array represents a knex.js query builder that is prepared to be executed and generates a promise. Is there a way to execute each element of this dynamically built array sequentially? let ...

Storing a JSON object within a data attribute in HTML using jQuery

In my HTML tag, I am storing data using the data- method like this: <td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td> When retrieving the data in a callback, I use: $(this) ...

Shuffle letters in a word when hovered over, then unscramble them back to their original order

I have noticed a fascinating effect on several websites. To give you an idea, here are two websites that showcase this effect: Locomotive and TUX. Locomotive is particularly interesting to look at as the desired effect can be seen immediately when hovering ...