query javascript object

2020-02-09 12:08发布

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.

2条回答
叼着烟拽天下
2楼-- · 2020-02-09 12:23
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];
    }
  }
}
查看更多
够拽才男人
3楼-- · 2020-02-09 12:25

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)

查看更多
登录 后发表回答