使用节点js迭代json数组对象

时间:2015-11-02 13:30:48

标签: javascript arrays json node.js

我有一个任务来遍历包含json数组的复杂json文件。我无法从json文件访问数组对象。

  

我需要从json访问特别是class-name对象   文件。

classdetail.json

[ [ {   "student" : [ 
     {
     "name" : "AAaa",
     "class-name" : "A",
     "grade-label" : "AA"   }, 
     {
     "name" : "AAbb",
     "class-name" : "A",
     "grade-label" : "AB"   }, 
     {
     "name" : "AAcc",
     "class-name" : "A",
     "grade-label" : "AB"   }, 
     {
     "name" : "AAdd",
     "class-name" : "B",
     "grade-label" : "AA"   } ],  
      "Average" : 2.5 },

      {   
     "student" : [ 
      {
     "name" : "BBaa",
     "class-name" : "B",
     "grade-label" : "AB"   }, 
      {
     "name" : "BBbb",
     "class-name" : "B",
     "grade-label" : "AA"   }, 
      {
     "name" : "BBcc",
     "class-name" : "B",
     "grade-label" : "AA"   }, 
      {
     "name" : "BBdd",
     "class-name" : "B",
     "grade-label" : "AA"   } ],   
      "Average" : 2.5 } ] ]

iterate.js

var fs = require('fs');
var express = require('express');
var http = require('http');
var publicApis;
var item;
var subItem;


classmem = JSON.parse(fs.readFileSync("classdetail.json", "utf8"));



for (item in classmem) {
  for (subItem in classmem[item]) {
     console.log(classmem[item][subItem]);
  }
}

3 个答案:

答案 0 :(得分:1)

for (item in classmem) {
  for (subItem in classmem[item]) {
     var student = classmem[item][subItem].student;
     for (row in student) {
       console.log(student[row]['class-name']);
     }
  }
}

但请阅读Array.forEach

答案 1 :(得分:0)

for...in以任意顺序迭代对象属性。它可能不是您想要用于数组的数组,该数组以明确定义的顺序存储项目。 (虽然它应该适用于这种情况)

尝试Array.forEach()

// iterate over `classmem`
classmem.forEach(function(element, index, array) {
  // iterate over classmem[index], which is an array too
  element.forEach(function(el, idx, arr) {
    // classmem[index][idx] contains objects with a `.student` property
    el.student.forEach(function(e, i, a) {
      console.log(e["name"], e["class-name"], e["grade-label"]);
    });
  });
});

答案 2 :(得分:0)

首先检查值是否为数组然后访问"类名"值

for (item in classmem) {
    for (subItem in classmem[item]) {
        **if (typeof classmem[item][subItem] === 'object') {
            classmem[item][subItem].forEach(function (val, ind) {
                console.log(val['class-name']);
            });
        }**
    }
}