views:

147

answers:

2

I need to find out if an id occurs in my JSON object, for example:

{
  "requested": "2009-07-25T14:12:25+01:00",
  "channels": [
    {"id": 1, "name": "General", "created": "2009-07-25 14:00:02"}
  ]
}

Specifically I need to check if my id (say, 2) occurs in channels.i.id. How can this be done?

+2  A: 

Try this:

var id = 2,
    found = false;
for (var i=0; i<channels.length; i++) {
    if (channels[i].id == id) {
        found = true;
        break;
    }
}
Gumbo
A: 

Or more succinctly and probably faster :

var id = 2; 
for (var found, i = channels.length; i && !(found = channels[--i] === id);)
  ;
Hans B PUFAL
@Gumbo's answer is much clearer though, and I doubt there's a significant speed difference, if any.
Matthew Crumley