ES6-遍历JSON

时间:2018-10-22 04:30:12

标签: javascript json ajax ecmascript-6 es6-promise

问题陈述

我从API访问JSON -我们将此API称为#1。下面列出了示例数据。本质上包含论坛信息主要是帖子

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

我也从另一个API访问JSON-我们将此API称为#2。这些数据包含个人信息。

[
  {
    "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"
      }]

我想获取所有唯一的名称,并将每个名称放在API#2中带有“ User”类的div中。

然后,我希望使用匹配的“ id”字段将API#1中的每个帖子显示在API#2中的每个用户下方。

我到目前为止所得到的

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

以上输出实质上是API#2中显示的原始数据。尚未处理。

我不确定该怎么做

  1. 需要使用map,reduce或其他可能的方法来遍历API#2中的每个名称并创建一个div
  2. 需要使用循环遍历API#1中的每个帖子,然后如果它与'id'字段匹配,则将其粘贴到特定用户的div下

更新

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

返回并输出名称列表:

Name 1
Name 2
Name 3

我现在只需要使用ID将帖子与姓名交叉匹配

2 个答案:

答案 0 :(得分:0)

要开始,您可以执行以下操作:

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

像对待其他任何JavaScript对象一样处理myJson。您可以过滤唯一值,并在数据数组上调用foreach。

您可以使用jquery或其他库比串联字符串更简洁地构建HTML,这只是出于说明目的。

答案 1 :(得分:0)

我不知道这是否是您要寻找的东西。

此代码示例假定您已经进行了调用以获取API1和API2的结果。

然后,为简化起见,我将用户数组转换为用户对象。这些对象的键是用户ID,而对象的值是原始值。

这允许您执行以下操作:从主题中快速查找用户:

    let user = userList[topic.userId];

然后我有一个循环,将主题数组从对象结构转换为字符串数组。然后将它们连接成一个字符串,并用'\n'分隔它们。

然后将此字符串插入应该包含生成的HTML的div中。

// 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>