Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query javascript object

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.

like image 352
Darksbane Avatar asked Jan 18 '12 15:01

Darksbane


1 Answers

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)

like image 97
Adam Rackis Avatar answered Oct 19 '22 04:10

Adam Rackis