0

I am trying to do a very basic loop over a object that I am getting from my json file:

// Look in the json file and loop over the data we need for this chart
$.each(jsonResponse.data.escalationsSubmittedByLocation.dataset, function() {
     tempData.push(Array(this.loc, parseInt(this.total)))
})

When I debug and check the data I am looping over, its showing the correct object:

enter image description here

The issue however is as soon as I am inside the loop and I try to refer to the object using this.loc or this.total it cannot find it.

enter image description here

In the picture above, I am hovering over line 676 which is the data object I am looping over. As you can see, its an object that contains both the total and loc.

However, when you look at the line I am debugging, this is referring to the values as a string or something.

Any idea as to why I can't access the values in the object I am looping over when the object clearly exists?

Additional Details:

// When called, we render the charts based on the json file that was created
        function doRender() {

            $.getJSON(jsonFile, function(data) {

                jsonResponse = data;
                tempData.length = 0;

                // Look in the json file and loop over the data we need for this chart
                $.each(jsonResponse.data.escalationTypes.dataset, function() {
                    tempData.push(Array(this.reason, parseInt(this.total)))
                })
... Chart Uses the Array Data Here ...
SBB
  • 8,560
  • 30
  • 108
  • 223

1 Answers1

0

This should work (and it works in jsfiddle) :

obj = {"total" : "foo", "loc" : "bar"};
tempData = [];
tempLoop = [];
    $.each(obj, function(index, value) {
        tempLoop[index] = value;
        if (index === "loc") {
            tempData.push(tempLoop);
        }
    })
console.log(tempData);

The callback function in $.each have the index and value parameters and you need these to pass keys and values in the loop. The loop process an array element every iteration, so you need to build by yourself the final array you want to get.

Anarcociclista
  • 313
  • 2
  • 11
  • SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data – SBB Apr 22 '15 at 19:03
  • This is wrapped inside of `$.getJSON(jsonFile, function(data) {` if that matters. I then define the data that I use in the mentioned query `jsonResponse = data;` – SBB Apr 22 '15 at 19:04
  • I found the problem: you forgot to use the `index' and 'value' parameters. – Anarcociclista Apr 22 '15 at 19:57