(ES6)无法访问JSON数据(未定义的错误)

时间:2018-06-13 13:13:41

标签: javascript json ecmascript-6

我有这个JSON文件,其中包含2个联系人的数据。

{
   "results":[
      {
         "gender":"female",
         "name":{
            "title":"Ms",
            "first":"Leonie",
            "last":"Otto"
         },
         "location":{
            "street":"3076 raiffeisenstraße",
            "city":"meißen",
            "state":"sachsen-anhalt",
            "postcode":62480
         },
         "email":"leonie.otto@example.com",
         "login":{
            "username":"bigwolf465",
            "password":"stephane",
            "salt":"Ip5qcgs5",
            "md5":"fe5df54750c64b7c5d54c92f0cb91f11",
            "sha1":"17d255fb64135b5e247a4ef5554557a1d2a8881e",
            "sha256":"341d750fce611b853b4f27d485f10ef9f9c3add4de12a7fbf838a1fd2d5168a9"
         },
         "dob":"1955-01-08 01:03:55",
         "registered":"2012-07-07 16:42:10",
         "phone":"0265-7006038",
         "cell":"0178-0561111",
         "id":{
            "name":"",
            "value":null
         },
         "picture":{
            "large":"https://randomuser.me/api/portraits/women/8.jpg",
            "medium":"https://randomuser.me/api/portraits/med/women/8.jpg",
            "thumbnail":"https://randomuser.me/api/portraits/thumb/women/8.jpg"
         },
         "nat":"DE",
         "status": "online"
      },
      {
         "gender":"female",
         "name":{
            "title":"Miss",
            "first":"Olive",
            "last":"Wright"
         },
         "location":{
            "street":"2912 manukau road",
            "city":"timaru",
            "state":"otago",
            "postcode":30721
         },
         "email":"olive.wright@example.com",
         "login":{
            "username":"brownrabbit413",
            "password":"derek",
            "salt":"gRxy7hHq",
            "md5":"dc214ffe467373790c8500abd1ff0f8f",
            "sha1":"7b7847e1a9e3b3de081e3eeebf972dc5d2b5527a",
            "sha256":"1763dff5c43e1cea431d1ad8c1648c586af9d1e1410001d743078af143ce30b9"
         },
         "dob":"1982-07-01 12:12:29",
         "registered":"2016-03-25 19:15:33",
         "phone":"(003)-127-5232",
         "cell":"(133)-307-2001",
         "id":{
            "name":"",
            "value":null
         },
         "picture":{
            "large":"assets/img/users/233899238.jpg"
         },
         "nat":"NZ",
         "status": "online"
      }
   ],
   "info":{
      "seed":"0c15ba34c943fa7f",
      "results":10,
      "page":1,
      "version":"1.1"
   }
}

我想创建一个列表,显示JSON文件中的所有联系人。我想显示名称,图片和用户名。 我试着用这个js代码做到这一点:

{

  const createContacts = results => {

    const $li = document.createElement(`li`);
    $li.classList.add(`contact`);
    $li.dataset.username = results.login.username;
    document.querySelector(`.contacts-list`).appendChild($li);

    const $divWrap = document.createElement(`div`);
    $divWrap.classList.add(`wrap`);
    $li.appendChild($divWrap);

    const $span = document.createElement(`span`);
    $span.classList.add(`contact-status ${results.status}`);
    $divWrap.appendChild($span);

    const $img = document.createElement(`img`);
    $img.src = results.picture.large;
    $img.setAttribute(`alt`, `${results.name.first}`);
    $divWrap.appendChild($img);

    const $divMeta = document.createElement(`div`);
    $divMeta.classList.add(`meta`);
    $li.appendChild($divMeta);

    const $name = document.createElement(`p`);
    $name.classList.add(`name`);
    $name.textContent = `${results.name.first} ${results.name.last}`;
    $divMeta.appendChild($name);

    const $preview = document.createElement(`p`);
    $preview.classList.add(`preview`);
    $preview.textContent = `${results.login.username}`;
    $divMeta.appendChild($preview);

  };

  const makeContacts = results => {
    results.forEach(result => {
      createContacts(results);
    });
  };
  const parse = results => {
    makeContacts(results);
  };

  const init = () => {
    const jsonFile = `./assets/data/users.json`;
    fetch(jsonFile).then(r => r.json()).then(data => parse(data.results));

  };
  init();
}

我一直收到这个错误。

script.js:7 Uncaught (in promise) TypeError: Cannot read property 'username' of undefined

有人知道我做错了什么吗?好像我无法访问JSON数据。

4 个答案:

答案 0 :(得分:3)

您正在将results数组传递给createContacts(results);

将其更改为:

const makeContacts = results => {
    results.forEach(result => {
      createContacts(result);
    });
  }; 

答案 1 :(得分:0)

您将results数组传递给函数createContacts。像这样改变:

const makeContacts = results => {
    results.forEach(result => {
      createContacts(result);
    });
};

答案 2 :(得分:0)

由于results是一个列表,而不是一个对象,因此您只能键入results.login,因为这将返回undefined。 或者,您可以使用结果索引,例如results[0].login.username

这里最好的方法是遍历结果数组。

const createContacts = results => {
    results.forEach(item => {
        const $li = document.createElement(`li`);
        $li.classList.add(`contact`);
        $li.dataset.username = item.login.username;
        document.querySelector(`.contacts-list`).appendChild($li);
    })
    ...
    ...
}

答案 3 :(得分:0)

您正在将results数组传递给createContacts函数而不是result(该数组的单个元素)。

您可以通过更改代码来修复它:

const makeContacts = results => {
  results.forEach(result => {
    createContacts(result);
  });
};