0

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.

Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • Try to access like this data['graph_data'][0].x because your array is an object. – McBern Oct 09 '18 at 11:18
  • did you get the coordinate values from the ways you've mentioned and just want help with iterating over them? – gavin Oct 09 '18 at 11:19
  • @McBern is that not the same as `data['graph_data']['0']['x']` just using different syntax? – Mark Schultheiss Oct 09 '18 at 11:20
  • ['x'] that operator is for non-object array. the . operator is for object array – McBern Oct 09 '18 at 11:23
  • `data['graph_data'][0].x` - gives me `undefined` – Ryan H Oct 09 '18 at 11:23
  • 1
    @McBern That is [not true](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json). The square brackets can be used for both objects and arrays. – str Oct 09 '18 at 11:29

4 Answers4

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>
SilentCoder
  • 1,970
  • 1
  • 16
  • 21
  • This worked! How can I combine all of the X values into one variable separated by a comma width braces each side E.g: [20,10,40,30] – Ryan H Oct 09 '18 at 11:36
  • I have edit. Add values to array and use `array.join()` – SilentCoder Oct 09 '18 at 11:43
  • 1
    "[As of jQuery 3.0, `$.parseJSON` is deprecated. To parse JSON strings use the native `JSON.parse` method instead.](https://api.jquery.com/jQuery.parseJSON/)" – str Oct 09 '18 at 11:51
0

Use JQuery like this:

$.each(data['graph_data'],function(index,data){
  console.log(data.x);
  console.log(data.y);
})
McBern
  • 549
  • 1
  • 4
  • 8
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

emil
  • 6,074
  • 4
  • 30
  • 38
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);
  }
}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100