0

I've created a JSON object which has two arrays in it. I've searched all over the web on how to extract the data but all the code I've tried has either returned "undefined" or [object object].

Can you please look at my example and show me how I would do this?

<html>
 <head>
     <title> New Document </title>
  <meta name="Generator" content="NPP-Plugin">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>
 <body>
 <div id="file"></div>
 <div id="applicID"></div>
  <script type="text/javascript">
var IETMObj = {
    "allItems": [{ 
         "sFile": "Test.html",
         "Applicability": [{   // second dimension
                            "ApplicID": "subj_1",
                            "ApplicDisp": "Driving",
                            "Condition": "In rain"
                    },{
                            "ApplicID": "subj_2",
                            "ApplicDisp": "Running",
                            "Condition": "Uphill"
                    }]
            }]
  };

  for (var i = 0; i < IETMObj.length; i++){
      document.write("<br><br>array index: " + i);
  var obj = IETMObj[i];
  for (var key in obj){
    var value = obj[key];
    document.write("<br> - " + key + ": " + value);
  }
}


  </script>
 </body>
</html>
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
mightymax
  • 431
  • 1
  • 5
  • 16
  • `IETMObj` is an object, not an array. – Barmar May 05 '17 at 20:33
  • The array you want to process is `IETMObj.allItems[0].Applicability` – Barmar May 05 '17 at 20:35
  • @Barmar I'm afraid I couldn't get your correction to the code working. http://js.do/MHammett/multidimensionalobj And I looked at the other questions, and tried their solutions. They didn't work in my case. Which is why I reached out for help. – mightymax May 06 '17 at 04:29
  • Try `var applicability = IETMObj.allItems[0].Applicability;` then loop through `applicability` the way you're looping through `IETMObj` in your code. – Barmar May 06 '17 at 11:02

1 Answers1

0

ITEMObj is an object, not an array. The array you want to loop through is IETMObj.allItems[0].Applicability.

var applicability = IETMObj.allItems[0].Applicability;
for (var i = 0; i < applicability.length; i++) {
    document.write("<br><br>array index: " + i);
    var obj = applicability[i];
    for (var key in obj){
        var value = obj[key];
        document.write("<br> - " + key + ": " + value);
    }
}

And if there can be more than one item in allItems, you should have an outer loop for them.

Barmar
  • 741,623
  • 53
  • 500
  • 612