0

My Json array looks like this:

var data =
{
    "categories": 
    {
        "category1": 
        {
            "Name": "Maps",
             "Id": 3,
             "orderInList": 1
        },
        "category2": 
        {
            "Name": "Books",
            "Id": 2,
            "orderInList": 2
        }
    }
};

When I write do console.log(data), the 'key' to the object is formatted like:

|         key           |    value  |

categories[category1][Id]     "3"

How can I iterate over this in a for loop (without using JQuery's $.each) so I can tell which key, value pairs are Names, Id's or orderInList's?

Working Jsfiddle

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Kiada
  • 679
  • 3
  • 15
  • 24
  • 5
    That's a JavaScript object literal, it isn't JSON and none of the values are arrays. – Quentin Aug 13 '12 at 13:13
  • http://jsfiddle.net/rlemon/tzUWP/1/ are you just trying to do this? – rlemon Aug 13 '12 at 13:16
  • possible duplicate of [I have a nested data structure / JSON, how can access a specific value?](http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-access-a-specific-value) – Esailija Aug 13 '12 at 13:18
  • ah alright, sorry if I'm confusing the terminology - I'm just trying to grasp what's going on really. If it isn't an array then I'm probably asking the wrong question hrrm. Can I pick things straight out of the data variable then? like var name = categories.category1.name? – Kiada Aug 13 '12 at 13:19
  • @Quentin You mean it's not JSON because there's too many closing braces `}` or am I missing something else? – Sean Bone Aug 13 '12 at 13:26
  • @SeanBone — It isn't JSON because it starts with `var data =` and ends in `;`. – Quentin Aug 13 '12 at 13:30

3 Answers3

1

Your outer categories object is an object that contains many child objects. You can iterate through these children objects using a for...in loop.

for (var category in data.categories) {
    // here you can access `category.Name`, `.Id`, and `.orderInList`
}
jbabey
  • 45,965
  • 12
  • 71
  • 94
1

Something like this should work:

for (var category in data['categories']) {
    for (var key in data['categories'][category]) {
        var value = data['categories'][category][key];

        // Now do whatever you want based on key...
        switch (key) {
           case 'Name':
              // Whatever
              break;
           default:
              break;
        }
    }
}

In any case, key and value in the inner loop will hold the key and value of your nested object, and category will hold the category.

The potentially confusing thing about this is that object properties can be accessed like array values in Javascript.

So consider the code below:

var some_object = {
    a: 0
};

// These two lines do the same thing, even though some_object is not an array.
some_object.a = 1;
some_object['a'] = 1;
Telgin
  • 1,614
  • 10
  • 10
  • Thanks for this. It looks like it gets quite complicated! I can't seem to get this to work in jsfiddle though hrrm. Nothing gets logged to the console when I write console.log(value). http://jsfiddle.net/tzUWP/3/ – Kiada Aug 13 '12 at 13:35
  • @CraigWhitley I tested it out, and the reason it's not working in jsfiddle is because of something related to the $.ajax bit. I don't know anything about jsfiddle, but I tried attaching just show_response(data) to the button and it works for me. – Telgin Aug 13 '12 at 13:41
  • You're right, works perfectly when I strip the ajax request away. Thanks! – Kiada Aug 13 '12 at 13:50
0

Checkout this

var data = {
  "categories": {
    "category1": {
        "Name": "Maps",
        "Id": 3,
        "orderInList": 1
    },
    "category2": {
        "Name": "Books",
        "Id": 2,
        "orderInList": 2
    }
  }
};

function represent(obj) {
  var reprs = [];
  for (var key in obj) {

    if(!obj.hasOwnProperty(key)) continue;
    if (obj[key] instanceof Object) {
        var result = represent(obj[key]);
        for (var i = 0; i < result.length; i++) {
            reprs.push("[" + key + "]" + result[i]);
        }
    }
    else {
        reprs.push("[" + key + "] = " + obj[key]);
    }
  }
  return reprs;
}

console.log(represent(data));
//output

["[categories][category1][Name] = Maps",
 "[categories][category1][Id] = 3",
 "[categories][category1][orderInList] = 1",
 "[categories][category2][Name] = Books",
 "[categories][category2][Id] = 2",
 "[categories][category2][orderInList] = 2"]

which key, value pairs are Names, Id's or orderInList's?

I think you can add code at the recursion terminate condition to check if the key is equal to Names Id or orderInList

xiaowl
  • 5,177
  • 3
  • 27
  • 28