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

6
  • 5
    That's a JavaScript object literal, it isn't JSON and none of the values are arrays. Commented Aug 13, 2012 at 13:13
  • jsfiddle.net/rlemon/tzUWP/1 are you just trying to do this? Commented Aug 13, 2012 at 13:16
  • possible duplicate of I have a nested data structure / JSON, how can access a specific value? Commented Aug 13, 2012 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? Commented Aug 13, 2012 at 13:19
  • @Quentin You mean it's not JSON because there's too many closing braces } or am I missing something else? Commented Aug 13, 2012 at 13:26

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

3 Comments

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). jsfiddle.net/tzUWP/3
@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.
You're right, works perfectly when I strip the ajax request away. Thanks!
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`
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.