Iterating json array objects using node js

12,102
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']);
     }
  }
}

But read about Array.forEach.

Share:
12,102
Ananth
Author by

Ananth

Updated on June 14, 2022

Comments

  • Ananth
    Ananth almost 2 years

    I have got a task to iterate through the complex json file that contains json array. I could not access the array object from the json file.

    I need to access the particularly the class-name object from the json file.

    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]);
      }
    }