Ryan H
Ryan H

Reputation: 2953

Trying to access key in JSON array

I'm trying to integrate Chart JS into a project. I have some JSON data that is returned via Ajax using the following:

$(".symptom-graph").each(function(){
    Tygh.$.ceAjax(
      'request',
      fn_url('symptom_tools.ajax_symptom_graph'),
      {
        data:{
          symptom_ids: $(this).data('symptom-id')
        },
        callback: function(data) {
          $(".symptom-graph").each(function(){
            if($(this).data('symptom-id') == data['symptom_ids'])
            {
              //TODO: load up graph stuff here
              $(this).html(data['graph_data']);
            }
          });
        }

      }
    );
  });

The above code returns the following JSON data:

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

I'm trying to access each item in the array and pull out either the X or Y coordinate so that the data: [] array in my Chart JS script has the each of the items.

I've tried the following to access either the Y or X coordinate:

data['graph_data']['0']['y']

data['graph_data'][0]['y']

data['graph_data']['y']

data['graph_data'][0]

Not sure how I'd loop over each one either.

Any guidance/solutions would be helpful, thanks.

Upvotes: 0

Views: 114

Answers (4)

Mark Schultheiss
Mark Schultheiss

Reputation: 34196

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

Upvotes: 0

SilentCoder
SilentCoder

Reputation: 2000

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>

Upvotes: 1

emil
emil

Reputation: 6364

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

Upvotes: 0

McBern
McBern

Reputation: 549

Use JQuery like this:

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

Upvotes: 0

Related Questions