Chartjs-Trying to access key in JSON array

1๐Ÿ‘

โœ…

You can use $.each() function also, and use jQuery.parseJSON(YourJsonDataSet)

var xArray = [];

$(document).ready(function(){
var data = jQuery.parseJSON('[{"x": "0","y": "35"}, {"x": "1","y": "6"}, {"x": "2","y": "3"}, {"x":"3","y": "11"}, {"x": "4","y": "2"}]');

$.each(data,function(index, value){
    console.log("X - "+ value.x + " and Y - " +value.y)
   xArray.push(value.x);
});

alert(xArray.join())

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0๐Ÿ‘

Use JQuery like this:

$.each(data['graph_data'],function(index,data){
  console.log(data.x);
  console.log(data.y);
})

0๐Ÿ‘

You can either iterate with plain loop statements like for, or as you use jQuery, utilize $.each.

var i;
for (i = 0; i < data.graph_data.length; i += 1) {
  // data.graph_data[i].x
  // data.graph_data[i].y
}

OR

$.each(data.graph_data, function(item) {
  // item.x
  // item.y
});

In modern browsers which allows EcmaScript 6, you can use Array.forEach as @Mamun answered. To see if you can use it in your browser, check it out at https://caniuse.com/#search=foreach

0๐Ÿ‘

However you derive that array as an object you can then iterate it. Not sure if this does answer your question.

var mythings = [{
  "x": "0",
  "y": "35"
}, {
  "x": "1",
  "y": "6"
}, {
  "x": "2",
  "y": "3"
}, {
  "x": "3",
  "y": "11"
}, {
  "x": "4",
  "y": "2"
}];

for (var i = 0; i < mythings.length; i++) {
  console.log("y:", mythings[i].y);
  console.log("x:", mythings[i]["x"]);
}
// access via keys
for (var n = 0; n < mythings.length; n++) {
  var keyNames = Object.keys(mythings[n]);
  console.log(keyNames);
  for (var name of keyNames) {
    console.log(name, mythings[n][name]);
    var value = mythings[n][name];
    console.log(value);
  }
}

Leave a comment