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

Exploring the magic of VueJS: Implementing computed properties for "set/get" functionalities in tandem with Vue.Draggable and

Currently, I am in need of assistance with utilizing "Vue.Draggable". For the past two days, I have been struggling to properly update the draggable array. The main challenge lies in: Updating the draggable array using computed set/get functions Obtaini ...

The output of the http.get or http.request callback is only visible within the shell when using node.js

Just dipping my toes into node and aiming to avoid falling into the callback hell trap. I'm currently working with two files: routes.js fetch.js //routes.js var fetchController = require("../lib/mtl_fetcher/fetcher_controller"); var express = requir ...

Struggling with the development of a crossfading image gallery using jQuery's .animate() function while ensuring compatibility with IE8

Seeking assistance in creating a crossfading image gallery using jQuery and the .animate() function. I'm struggling to solve the issue of smooth fadeIn for the next image while maintaining compatibility with IE8. https://jsfiddle.net/Vimpil/fqhc1e9m/ ...

What is the most efficient way to organize these arrays?

I've been racking my brain trying to figure out a sorting logic for some arrays, but I'm stumped. Maybe you have an idea? Imagine we have an array of objects structured like this: let obj = {day:'2', month:'6', year:'19 ...

Updating a .txt file using JavaScript

Is there a method on the client side to add text to a file called text.txt using JavaScript? In Python: f = open("text.txt","w") f.write("Hello World") f.close() The code snippet above would input "Hello World" into the text file. I am looking for a sim ...

Mongoose and ES6 promises are not delivering the expected results

I'm currently working on a piece of code that involves creating an array of promises to save specific numbers. The issue I'm facing is that when the output is printed, it displays the same record 10 times. Below is the code snippet: 'use s ...

Encounter the following issue: Unable to access property '0' due to being undefined

After restructuring my entire Javascript code, I managed to solve the problem with asynchronous calls. However, an error occurs when editing a repair and the server prompts the client for repair information again. The error message displayed is "Uncaught ...

Generating, establishing aesthetics for a specific span

My goal is to automatically detect addresses within a page and apply the class "address" where they are found. var addressPatternApplier = function(element, pattern, style) { var innerText = element.innerText; var matches = innerText.match(pattern); ...

Changing the route variable in React Native's bottom bar tab functionality

I am looking to create a consistent bottom tab bar that remains the same on every screen, but I want the routes of the tabs at the bottom to change dynamically. For example, in Screen1, the tab at the bottom should route to 'Screen2'. Then, when ...

What steps can be taken to ensure that the popover div remains visible when clicking inside it in a "dismissible popover" using Twitter Bootstrap with the data-trigger attribute set to "

I am struggling with a dismissible popover that contains a text box. When I click inside the text box to type, it disappears due to the "data-trigger="focus". Is there a way for the div not to disappear when clicked inside intelligently? Here is the releva ...

JsonResult from MVC contains information, yet the browser is devoid of any data

In my controller method GetLayer2(), it bears a striking resemblance to GetLayer0() and GetLayer1() [HttpGet] public async Task<JsonResult> GetLayer2(string datePassedIn, string eventType, string driverId) { string orgCode = "HVO"; //User.Identi ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

Express identifies the user, however, the username is displayed exclusively on one specific page. This situation may indicate a potential cookie problem

I am in the process of developing an express app integrated with MongoDB. The issue I am facing involves a pug template for the navigation bar where I aim to display the user's name at the top upon logging in. Strangely, it only works on the page that ...

"I am interested in using the MongoDB database with Mongoose in a Node.js application to incorporate the

I am facing a situation where I need to validate the name and code of a company, and if either one matches an existing record in the database, it should notify that it already exists. Additionally, when receiving data with isDeleted set to true, I want to ...

An issue arises in the NodeJS Express authentication process when attempting to set headers after they have already been sent,

Currently, I am working on developing a basic authentication system using the POST method. app.post("/api/auth",function(req,resp) { var username = req.body.username||req.param('username'); var password = req.body.password||req.param(&a ...

What could be causing the never-ending page reloads on a PWA Vue application?

I'm currently working on turning my Vue app into a PWA using the Vite-PWA-plugin (this plugin) However, I've encountered an issue where the page keeps reloading repeatedly when served from cache, especially when utilizing the Oauth2 protocol for ...

Nginx and Socket.io: Issues with client-server connection not functioning properly

Hello everyone! I am currently in the process of deploying my application, which utilizes React and NodeJs. However, I have encountered an issue with integrating Socket.io with Nginx. My approach involves editing the Nginx file using the command: sudo ...

Is there a way to showcase the generated results on a graph after the user presses the submit button?

I've been working with to generate a bar chart. Currently, when the user clicks 'submit', the input numbers are shown in a graph on http://jsfiddle.net/jx9sJ/5/. Now, I want to make some changes. I am attempting to send the input numbers t ...

How do I retrieve the child elements of an array from a JSON response in ReactJS?

After receiving JSON data: componentDidMount() { const {axios} = this.props const {invoice} = this.state axios({ method: 'get', url: `/invoice`, }).then((re ...

Encountering an issue with a loop in my jQuery function - any solutions?

Having encountered an issue with a select object not working in my form-building function, I resorted to using an ajax call to fetch data from a database table. While the network tab in Chrome shows the data being retrieved successfully, the console displa ...