ES6 - Looping Through JSON

Viewed 169

Problem Statement

I access JSON from an API -- let's call this API #1. Example data is listed below. Essentially contains forum information mainly posts

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

I access JSON from another API also -- let's call this API #2. This data contains personal information.

[
  {
    "id": 1,
    "name": "Lera",
    "username": "Lera2",
    "email": "Em@.com",
    "address": {
      "street": "GGa",
      "suite": "Ap3. 333",
      "city": "Gwee",
      "zipcode": "2222-3333",
      "geo": {
        "lat": "-11213",
        "lng": "312424"
      }]

I want to grab all unique names and place each name in a div with a class of "User" from API #2.

Then, I want each post from API #1 to be displayed under each user from API #2, using match "id" fields.

What I have got so far

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

Output of the above is essentially raw data as displayed in API #2. It is not processed yet.

What I am not sure how to do

  1. Need to use either map, reduce or possibly something else, to go through each name in API #2 and create a div
  2. Need to use a loop to go through each post in API #1 and then if it matches the 'id' field we paste it under the specific user's div

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>"; 
    });
});

Returns and outputs the list of names:

Name 1
Name 2
Name 3

I just need to cross-match the posts to the names using the ID now

2 Answers

To get you started, you could do something like this:

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("testDiv").innerHTML += "<div>" + user.name + "</div>"; 
    });
});

Treat myJson like any other JavaScript object. You can filter unique values and call foreach on the array of data.

You could use jquery or another library to more succinctly build HTML than concatenating strings, this is for illustrative purposes.

I have no idea if this is what you are looking for.

This code example assumes that you have already made the calls to get the results of API1 and API2.

Then, to simplify things I convert the user Array into a user Object. They keys of the Object are the userid and the values of the Object are the original values.

What this allows you to do is a faster lookup of the user from the topic:

    let user = userList[topic.userId];

Then I have a loop that converts the Topic Array from the object structure into an Array of strings. These are then joined into one string with '\n' separating them.

This string is then inserted into the div that should hold 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": "Em@.com",
    "address": {
      "street": "GGa",
      "suite": "Ap3. 333",
      "city": "Gwee",
      "zipcode": "2222-3333",
      "geo": {
        "lat": "-11213",
        "lng": "312424"
      }
    }
  },
  {
    "id": 2,
    "name": "John",
    "username": "Big John",
    "email": "bj@littlefoot.com",
    "address": {
      "street": "123 Street",
      "suite": "",
      "city": "Smallville",
      "zipcode": "12345-6789",
      "geo": {
        "lat": "-11213",
        "lng": "312424"
      }
    }
  }
];

// Convert from an array to an object with the user id as the key and the user info object and the value.
// This allows for simpler data access.
let userList = api2Resp.reduce(
  (newUserList, user) => {
    newUserList[user.id] = user;
    return newUserList;
  }, {}
);


// Generate all of the output
let html = api1Resp.map(
  topic => {
    // Try to get the user info from the topic
    let user = userList[topic.userId];
    // If user is undefined the it is 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>

Related