根据 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:30:10  来源:igfitidea点击:

Select from array of objects based on property value in JavaScript

javascriptjqueryasp.net-mvc

提问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 ObjectsListin the array matches. The above assumes that ObjectsListhas 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 forloop approach and a lot of people will wag a finger at me because they think continueis a bad word; if you don't like continuethen 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;
    }
}