-2

I want loop through a nested array inside a json object. My JSON looks like this when I receive it from a PHP function:

{
  "min": {
    "type": "select",
    "data": {
      "100000": "120,000",
      "120000": "200.000",
      "130000": "300.000"
    }
  },
  "max": {
    "type": "select",
    "data": {
      "100000": "120,000",
      "120000": "200.000",
      "130000": "300.000"
    }
  }
}

What I want is a loop which passes through each element in the "data" array. How can I achieve this. I'm pretty sure it must be something with jQuery.each.

es1
  • 1,231
  • 3
  • 14
  • 27
  • jQuery is a JavaScript library, so to do it in jQuery, you'd just use typical JavaScript syntax. Once you know how to do that, you can use other various iterators if you wish. – cookie monster Jun 07 '14 at 01:29
  • this is different from the "duplicate" post since I'm working with a plain json object, not javascript array – es1 Jun 07 '14 at 01:31
  • 1
    To work with JSON, you first need to parse it into JavaScript Arrays/Objects. Yours is no different from the duplicate. – cookie monster Jun 07 '14 at 01:32
  • I tried accessing the values through the properties, but I get error messages from Google Chrome Console – es1 Jun 07 '14 at 01:32
  • Read that other answer. It links to another answer which tells you how to first parse JSON. Your question was about looping through the data, which implies that it's already parsed. – cookie monster Jun 07 '14 at 01:33

1 Answers1

1

What you are looking for is the really cool for in loop in JavaScript.

for in loops grab your properties. Given your example JSON object a for in loop would look like and do the following:

for (var foo in theJSONObject) {
    // foo will be 'min', then 'max'
    // to access the sub-groups of min and max you just need another for in loop
    for (var spam in foo) { // Here we get 'type' and 'data'
         // Here is where JavaScript magic happens!
         theJSONObject[foo][spam];
         // on the first iteration the above line will access theJSONObject variable
         // like this theJSONObject.min.type
         // this is because the [] operators on an object will grab the property named
         // by what is passed in to them
         // example: myWolverineObject['numClaws'] is the same as
         //          myWolverineObject.numClaws
    }

}

Alternatively, you can use Object.keys(theJSONObject) to get an array of the properties of the object you can iterate through (in this case it would return ['min', 'max'] ).

In jQuery you can also do the following with the $.each operator

$.each (theJSONObject, function (key , value) {
    // The keys would be 'min' and 'max' and values would be 'type' and 'data' 
    // off the bat!!
});

Hope this helps!!

Sam-Graham
  • 1,254
  • 12
  • 20