【问题标题】:Node.JS - How to access Values of Dictionary within an Array of a Key in a Dictionary?Node.JS - 如何在字典中的键数组中访问字典的值?
【发布时间】:2015-08-07 12:50:45
【问题描述】:

我是 Node.JS 的新手,我能够解析 JSON 数据并执行控制台日志以打印出名称和徽章。

var details = JSON.parse(body);
console.log(details.name, details.badges.length);

但我不知道如何获取 bagdes 数组中的数据,例如 id、name、url。

我试过了

console.log(details.badges.length.id);

但是什么都没有出现。我怎样才能访问它?谢谢。

{
"name": "Andrew Chalkley",
"badges": [
    {
      "id": 49,
      "name": "Newbie",
      "url": "http:\/\/teamtreehouse.com\/chalkers",
      "icon_url": "https:\/\/achievement-images.teamtreehouse.com\/Generic_Newbie.png",
      "earned_date": "2012-07-23T19:59:34.000Z",
      "courses": [

      ]
    },
    {
      "id": 26,
      "name": "Introduction",
      "url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
      "icon_url": "https:\/\/achievement-images.teamtreehouse.com\/HTML_Basics.png",
      "earned_date": "2012-07-23T21:57:24.000Z",
      "courses": [
        {
          "title": "HTML",
          "url": "http:\/\/teamtreehouse.com\/library\/html",
          "badge_count": 1
        },
        {
          "title": "Introduction",
          "url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
          "badge_count": 1
        }
      ]
    }
}

【问题讨论】:

    标签: arrays json node.js dictionary


    【解决方案1】:

    是数组,所以需要索引,例如:details.badges[0].id

    这将返回第一个(索引 0)元素 id。

    .length只返回数组的长度,所以获取里面的数据是没有用的。

    【讨论】:

    • 谢谢丹尼尔。我明白了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 2018-09-12
    • 2021-09-20
    • 2020-06-01
    相关资源
    最近更新 更多