javascript 查询javascript对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8913011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
query javascript object
提问by Darksbane
Ive got a JSON string coming over and being assinged to a javascript object
我有一个 JSON 字符串过来并被分配到一个 javascript 对象
{
"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.
有没有办法在 javascript 中“查询”这个数据,这样我就可以搜索 460 的 ID 并返回 name 和 loc (除了循环遍历整个对象)?我可以使用 jQuery 和 Prototypejs。
回答by Adam Rackis
JavaScript arrays have a built-in filter method:
JavaScript 数组有一个内置的过滤器方法:
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)
(要支持旧浏览器,您需要从上面的链接中获取垫片)
回答by Kristian
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];
}
}
}