根据 JavaScript 中的属性值从对象数组中选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8306419/
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
Select from array of objects based on property value in JavaScript
提问by sergioadh
I have JSON objects that have several properties such as an id and name. I store them in a JavaScript array and then based on a dropdownlist I want to retrieve the object from the JavaScript array based on its id.
我有 JSON 对象,这些对象具有多个属性,例如 id 和名称。我将它们存储在一个 JavaScript 数组中,然后基于下拉列表,我想根据其 id 从 JavaScript 数组中检索对象。
Suppose an object has id and name, how do I select them from my array variable?
假设一个对象有 id 和 name,我如何从我的数组变量中选择它们?
var ObjectsList = data;
var id = $("#DropDownList > option:selected").attr("value");
ObjectsList["id=" + id];
回答by mu is too short
Since you already have jQuery, you could use $.grep
:
由于您已经拥有 jQuery,您可以使用$.grep
:
Finds the elements of an array which satisfy a filter function. The original array is not affected.
查找满足过滤器函数的数组元素。原数组不受影响。
So something like this:
所以像这样:
var matches = $.grep(ObjectsList, function(e) { return e.id == id });
that will leave you with an array of matching entries from ObjectsList
in the array matches
. The above assumes that ObjectsList
has a structure like this:
这将为您留下数组中匹配条目ObjectsList
的数组matches
。以上假设ObjectsList
具有如下结构:
[
{ id: ... },
{ id: ... },
...
]
If you know that there is only one match or if you only want the first then you could do it this way:
如果您知道只有一场比赛,或者您只想要第一场比赛,那么您可以这样做:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id != wanted_id)
continue;
m = a[i];
break;
}
// m is now either null or the one you want
There are a lot of variations on the for
loop approach and a lot of people will wag a finger at me because they think continue
is a bad word; if you don't like continue
then you could do it this way:
for
循环方法有很多变体,很多人会对我摇摆不定,因为他们认为这continue
是一个坏词;如果你不喜欢continue
那么你可以这样做:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id == wanted_id) {
m = ObjectsList[i];
break;
}
}