9

Ive got a JSON string coming over and being assinged to a javascript object

{
   "results":[
      {
        "id":"460",
        "name":"Widget 1",
        "loc":"Shed"
      },{
        "id":"461",
        "name":"Widget 2",
        "loc":"Kitchen"
      }]
}

Is there a way to "query" this data in javascript so I could search for an ID of 460 and get name and loc returned (other than just looping through the whole object)? I've got jQuery and Prototypejs available to use.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Darksbane
  • 205
  • 1
  • 3
  • 11
  • Please see this link http://stackoverflow.com/questions/4992383/use-jquerys-find-on-json-object – Grrbrr404 Jan 18 '12 at 15:49
  • possible duplicate of [Find object by id in array of javascript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) - please use the search before you ask a question. – Felix Kling Jan 18 '12 at 15:51
  • There is no way to "query" that data more efficiently unless you also provide sorted indexes and use binary search or something. If this isn't performance critical, that won't be needed and this is a duplicate. – Esailija Jan 18 '12 at 15:56
  • Thanks for the links, I did search for about a day and couldn't find anything helpful. Likely because I wasn't using array as one of my search terms. – Darksbane Jan 18 '12 at 16:16

2 Answers2

24

DEMO

JavaScript arrays have a built-in filter method:

var valuesWith460 = obj.results.filter(function(val) {
    return val.id === "460";
});

(to support older browsers you'll want to grab the shim from the link above)

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
1
function getInfoByID( id )
  var object = { ... };
  for(var x in object.results) {
    if(object.results[x].id == id) {
      return [object.results[x].loc, object.results[x].name];
    }
  }
}
Kristian
  • 21,204
  • 19
  • 101
  • 176