0

I am trying to loop though a JSON object in NODEJS.

I am trying to retrieve the value of for example var value = [table][row][0][STATE] or [table][row][1][STATE] or [table][row][2][STATE] but i am getting STATE undefined error ? Is this the correct way of looping through Json object ?

  data = JSON.parse(buffer);


     for (var obj in data) {
      if (data.hasOwnProperty(obj)) {
        console.log(obj); 

         if (obj == "table") {
          for (var prop in data[obj]) {
             if (data[obj].hasOwnProperty(prop)) {

                   console.log(prop + ':' + data[obj][prop][0]['STATE']);
                   console.log(prop + ':' + data[obj][prop][1]['STATE']);
                   console.log(prop + ':' + data[obj][prop][2]['STATE']);

                   console.log(prop + ':' + data[obj][prop][0]['COUNT']);
                   console.log(prop + ':' + data[obj][prop][0]['COUNT']);
                   console.log(prop + ':' + data[obj][prop][0]['COUNT']);                      
               }
             }
          }

        }
    }

JSON FILE

{  
   "table":[  
      {  
         "row":[  
            {  
               "STATE":"A"
            },
            {  
               "COUNT":"107"
            }
         ]
      },
      {  
         "row":[  
            {  
               "STATE":"I"
            },
            {  
               "COUNT":"92"
            }
         ]
      },
      {  
         "row":[  
            {  
               "STATE":"R"
            },
            {  
               "COUNT":"2"
            }
         ]
      }
   ]
}
user3846091
  • 1,625
  • 6
  • 24
  • 29
  • 1
    why are you not just using `var table = obj.table;` and then using `table.forEach(function(o) { var row = o.row; ... });`? (also you're using some questionable JS - instead of for/in, use `Object.keys(obj).forEach(...)`, and this JSON is very weird: why are these things not named properties by anonymous array positions?) – Mike 'Pomax' Kamermans Sep 02 '14 at 19:08

1 Answers1

1

Definitely some odd decisions in your looping. But, try this:

var json = {  
   "table":[  
      { "row":[  
            {"STATE":"A"},
            {"COUNT":"107"}
         ]
      },
      { "row":[  
            {"STATE":"I"},
            {"COUNT":"92"}
         ]
      },
      { "row":[  
            {"STATE":"R"},
            {"COUNT":"2"}
         ]
      }
   ]
};

var table = json.table;

for( var row in table ) {    
    for( var field in table[row] ) {
        console.log( 'State: ' + table[row][field][0].STATE);
        console.log( 'Count: ' + table[row][field][1].COUNT);
    }
}

Working jsfiddle: http://jsfiddle.net/pamsvofz/

Update: I'd like to add there really isn't a reason to have the additional row key in the JSON. It really just makes the nesting a little more complicated.

Tony
  • 2,473
  • 1
  • 21
  • 34