Github API打孔卡数据转换

时间:2018-11-14 13:30:29

标签: javascript arrays json fetch github-api

我想创建一个图形,以类似于this python script的方式显示Github PunchCard提供的信息,但是使用JavaScript,而是使用D3.js。我使用GET /repos/:owner/:repo/stats/punch_card

从Github API this way检索信息

现在,我陷入了如何修改响应以收集数据并按天/小时对其进行分类的问题,但是显然我无法访问该数组。到目前为止,我的代码如下:

const showGithubData = (user, repo) => {
    console.log(`Querying user  ${user} and repo ${repo}`);
    fetchPunchCard(repoUser.value, repoName.value).then((res) => {
        console.log(res);         
    })
};

const fetchPunchCard = async (username, repository) => {
   /*  GET / repos /: owner /: repo / stats / punch_card */
    const url = `https://api.github.com/repos/${username}/${repository}/stats/punch_card`;

    const api_call = await fetch(url);

    const data = await api_call.json();
    return { data }
};

我返回正确的值,但随后在同一函数中无法访问它们。如果在showGithubData()中执行console.log(res [0])时说未定义,但是在执行console.log(res)时我可以看到它返回了一个数组Arrays(3),像这样:

{data: Array(168)}
data: Array(168)
[0 … 99]
    0: Array(3)
        0: 0
        1: 0
        2: 0
      length: 3
      __proto__: Array(0)
    1: (3) [0, 1, 0]
    2: (3) [0, 2, 0]

我想访问所有这些职位(0是日,1是小时,2是提交次数)以创建我的图表,但是我不知道为什么不能。

我非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

有时,我们看到由console.log打印的对象不准确。 当我遇到此问题(找不到我应该在其中的密钥并且在console.log中看到)时,我将按照以下两个步骤操作:

  1. 打印类型:为确保是一个json对象,而不仅仅是一个字符串,在这种情况下,它是一个对象:console.log(typeof res); > object
  2. 打印对象的所有键:有时不显示实际键,但仍在其中:console.log(Object.keys(res)); > [ 'data' ]

正如您所看到的,我们找到了第2步的解决方案,访问所有值的关键是data,因此在您的情况下,我们需要执行res.data < / p>

IE:console.log(res.data[0]); > [ 0, 0, 0 ]