Ananth
Ananth

Reputation: 45

Iterating json array objects using node js

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

Upvotes: 2

Views: 12707

Answers (3)

ali khabbaz
ali khabbaz

Reputation: 1

first check the value is array then access to the "class-name" value

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

Upvotes: 0

Tomasz Jakub Rup
Tomasz Jakub Rup

Reputation: 10680

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.

Upvotes: 2

Dan O
Dan O

Reputation: 6090

for...in iterates over object properties in arbitrary order. It might not be what you want to use for an array, which stores items in a well-defined order. (though it should work in this case)

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

Upvotes: 0

Related Questions