Search code examples
javascriptarraysnode.jsjsonpug

Javascript loop through array of JSON objects finds instances but records them as undefined


I'm running a script within a Pug template. The script begins with reading in an array of JSON objects from MongoDB. The stringified array (data) is iterated through to access each JSON object (doc) using a for loop. Following this, I iterate through each object's key/value pairs (col), of which there are a fixed number (20).

  var data = !{JSON.stringify(response.features)}

  for(var doc = 0; doc <= data.length; doc++)
    for(var col = 1; col <= 20; col++)
      console.log(data[doc[col]])

There are 8 objects with 20 key/value pairs (columns) each. So the fact that I can see 180 returned undefined instances signals that the code is working fine, but I can't access or view the returned data for some reason? The end goal for this is to generate a table where each row corresponds to one object's key/value pairs.

Array Format: Array(8) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]

Object Format: Object { _id: "4598hs9h390b", name: "test feature", testValue: 3, … }


Solution

  • You are trying to access object properties with indices. What you need to do is use an iterator over the keys like Object.keys().

    Try this to get the data:

      var data = !{JSON.stringify(response.features)}
    
      for(var doc = 0; doc <= data.length; doc++)
        Object.keys(data[doc]).forEach(function(key,index) {
          console.log(data[doc][key])
      });
    

    or

      var data = !{JSON.stringify(response.features)}
    
      for(var doc = 0; doc <= data.length; doc++) {
         for(var col of Object.keys(data[doc])) {
            console.log(data[doc][col])
         }
      }