3

I'm failing to access the number inside the DATA array, which would be the ID mentioned in the COLUMNS.

My JSON is as follows:

{
  "COLUMNS": [
    "ID",
    "DESCRIPTION",
    "DATE"
  ],
  "DATA": [
    [
      53,
      "Try to do something test123",
      "September, 05 2017 00:00:00 +0100"
    ]
  ]
}

My current attempt was this, but with this, I get the whole 3 elements

  var jsonLength= JSON.DATA.length;

  for (dataIndex = 0; dataIndex < jsonLength; dataIndex++) {

      var dataLength= JSON.DATA[dataIndex].length;

      for (noteIndex = 0; noteIndex < dataLength; noteIndex++) {

          alert(JSON.DATA[dataIndex]);

      }
  }
2
  • have you tried like thisDATA[0][0] Commented Sep 5, 2017 at 8:42
  • Now I have thanks to Rory McCrossan's answer. Commented Sep 5, 2017 at 8:50

2 Answers 2

3

Your code is almost correct, you're just missing the second index accessor on your 2D DATA array. You can use the noteIndex incrementing variable from your loop:

var JSON = {
  "COLUMNS": [ "ID", "DESCRIPTION", "DATE" ],
  "DATA": [ 
    [ 53, "Try to do something test123", "September, 05 2017 00:00:00 +0100" ] 
  ]
}
var jsonLength = JSON.DATA.length;

for (dataIndex = 0; dataIndex < jsonLength; dataIndex++) {
  var dataLength = JSON.DATA[dataIndex].length;
  for (noteIndex = 0; noteIndex < dataLength; noteIndex++) {
    console.log(JSON.DATA[dataIndex][noteIndex]); // note the additional [] here
  }
}

Sign up to request clarification or add additional context in comments.

Comments

1
 var jsonLength= JSON.DATA.length;

  for (var i = 0; i < jsonLength; i++) {

      var note = JSON.DATA[i]
      var id = note[0] // access id value

  }

Also, if you are the owner of server, why not return more suitable and preferred json structure like this? :

[
    {"id": 1, "description": "..."},
    {"id": 1, "description": "..."}
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.