Node.JS-如何在字典的键数组中访问字典的值? [英] Node.JS - How to access Values of Dictionary within an Array of a Key in a Dictionary?

查看:46
本文介绍了Node.JS-如何在字典的键数组中访问字典的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new in Node.JS and I'm able to parse the JSON data and do a console log to print out name and badges.

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

但是我不知道如何获取数据(例如id,name,url)在bagdes数组中.

But I don't know how I can get the data inside the arrays of the bagdes such as id, name, url.

我尝试了

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

但是什么都没有出现.我该如何访问?谢谢.

But nothing shows up. How can I access that? Thank you.

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

推荐答案

它是一个数组,因此您需要索引,例如: details.badges [0] .id

It is an array, so you need the index, for example: details.badges[0].id

这将返回第一个(索引0)元素ID.

This will return the first (index 0) element id.

.length 仅返回数组的长度,因此在其中获取数据将无用.

.length only returns the length of the array, so it will not be useful to get the data in it.

这篇关于Node.JS-如何在字典的键数组中访问字典的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆