-1

I have a json response that looks a bit like this

[{"name":"Dude",       "id":"1",     "Category": "One"},
 {"name":"Guy,         "id":"12",    "Category": "One"},
 {"name":"Thomas"      "id":"12",    "Category": "Two"},
 {"name":"Richard",    "id":"2",     "Category": "One"},
 {"name":"Harold",     "id":"3",     "Category": "One"},
 {"name":"Pete",       "id":"4",     "Category": "Two"}]

I'd like to be able to loop through this object, and make a neat array of all the different kinds of categories, for example,

["One", "Two"]

if I were to loop through this one. I've tried to create a for/if loop that would ignore a category if it's already been mentioned, but with little success. is there a better way of doing this?

Captain Dando
  • 497
  • 2
  • 11
  • 30
  • You can review this question http://stackoverflow.com/questions/3586274/select-into-json – pegatron Mar 14 '13 at 07:54
  • I researched this question to the best of my abilities, searching google didn't yield this answer and considering it's title and contents I don't know how you came across it – Captain Dando Mar 14 '13 at 07:57
  • Not to mention the question you've linked me to is for a different situation, hard to understand, and many times longer and less efficient than the answer T.J Crowder has posted below. If I hadn't asked this question I would have been left with that as a last resort (If I found it). and now I'm getting downvoted for it? – Captain Dando Mar 14 '13 at 08:07
  • 1
    It has nothing to do with it. Just I gave you an idea for solution on the link. – pegatron Mar 14 '13 at 08:51
  • Thanks anyway, your intentions were good – Captain Dando Mar 14 '13 at 09:13

1 Answers1

5

Assuming you've deserialized that JSON response into the array containing objects you've shown (let's call it yourArrayOfObjects), it's simple to loop through and build the array:

var categories = [];
$.each(yourArrayOfObjects, function(index, entry) {
    if ($.inArray(entry.Category, categories) === -1) {
        categories.push(entry.Category);
    }
});

That uses $.each to loop through the array, and $.inArray to check whether we've already seen a category.

You could also do this without jQuery using Array#forEach (an ES5 addition, present on all modern browsers but missing, obviously, from some older ones) and Array#indexOf (missing from IE7 down), both of which are probably handled by any "ES5 shim" you might want to find and use.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875