从JSON数组中选择第一个元素,没有带jquery的标识符

时间:2022-07-28 03:36:36

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

我无法访问DATA数组中的数字,这将是COLUMNS中提到的ID。

My JSON is as follows:

我的JSON如下:

{
  "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

我目前的尝试就是这个,但有了这个,我得到了整个3个元素

  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 个解决方案

#1


4  

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:

您的代码几乎是正确的,您只是缺少2D DATA阵列上的第二个索引访问器。您可以使用循环中的noteIndex递增变量:

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
  }
}

#2


2  

 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? :

此外,如果您是服务器的所有者,为什么不返回更合适和首选的json结构? :

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

#1


4  

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:

您的代码几乎是正确的,您只是缺少2D DATA阵列上的第二个索引访问器。您可以使用循环中的noteIndex递增变量:

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
  }
}

#2


2  

 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? :

此外,如果您是服务器的所有者,为什么不返回更合适和首选的json结构? :

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