jQuery Jquery如何通过数组中的属性查找对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5579678/
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-26 19:24:24  来源:igfitidea点击:

Jquery how to find an Object by attribute in an Array

jquerycollectionsfiltertraversal

提问by Jesper R?nn-Jensen

Given I have an array of "purpose" objects:

鉴于我有一组“目的”对象:

//array of purpose objects:
var purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

(for simplicity i am omitting other attributes)

(为简单起见,我省略了其他属性)

Now I want to have a method that returns a specific one of the objects if a matching purpose name is found.

现在我想要一个方法,如果找到匹配的目的名称,它会返回一个特定的对象。

This is not working:

这不起作用:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(){
      return this.purpose == purposeName;
    });
};

findPurpose("daily");

but it actually returns an empty array:

但它实际上返回一个空数组:

[]

I am using JQuery 1.5.2. I have also tried with $.each() but with no luck. Apparently, most JQuery methods are designed for usage with DOM elements (such as filter().

我正在使用 JQuery 1.5.2。我也试过 $.each() 但没有运气。显然,大多数 JQuery 方法是为与 DOM 元素(例如filter().

Any ideas on how to achieve this?

关于如何实现这一目标的任何想法?

采纳答案by Jesper R?nn-Jensen

The error was that you cannot use thisin the grep, but you must use a reference to the element. This works:

错误是您不能this在 grep 中使用,但必须使用对元素的引用。这有效:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(n, i){
      return n.purpose == purposeName;
    });
};

findPurpose("daily");

returns:

返回:

[Object { purpose="daily"}]

回答by Luca Fagioli

Use this function:

使用这个功能:

function findObjectInArrayByProperty(array, propertyName, propertyValue) {
    return array.find((o) => { return o[propertyName] === propertyValue });
}

So, in your case:

所以,在你的情况下:


const purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

findObjectInArrayByProperty(purposeObjects, "purpose", "weekly");

// output -> {purpose: "weekly"}

More about the findmethod here.

更多关于这里find方法。

回答by Andrei

you should pass reference on item in grep function:

您应该在 grep 函数中传递对 item 的引用:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(item){
      return item.purpose == purposeName;
    });
};

Example

例子

回答by Johann

I personally use a more generic function that works for any property of any array:

我个人使用一个更通用的函数,适用于任何数组的任何属性:

function lookup(array, prop, value) {
    for (var i = 0, len = array.length; i < len; i++)
        if (array[i] && array[i][prop] === value) return array[i];
}

You just call it like this:

你只是这样称呼它:

lookup(purposeObjects, "purpose", "daily");

回答by jbobbins

Use the Underscore.js findWhere function (http://underscorejs.org/#findWhere):

使用 Underscore.js findWhere 函数 ( http://underscorejs.org/#findWhere):

var purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

var daily = _.findWhere(purposeObjects, {purpose: 'daily'});

dailywould equal:

daily将等于:

{"purpose":"daily"}

Here's a fiddle: http://jsfiddle.net/spencerw/oqbgc21x/

这是一个小提琴:http: //jsfiddle.net/spencerw/oqbgc21x/

To return more than one (ifyou had more in your array) you could use _.where(...)

要返回多个(如果您的数组中有更多),您可以使用_.where(...)

回答by Kalim

Best, Fastest way is

最好,最快的方法是

function arrayLookup(array, prop, val) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i].hasOwnProperty(prop) && array[i][prop] === val) {
            return array[i];
        }
    }
    return null;
}

回答by Douglas

If your array is actually a set of JQuery objects, what about simply using the .filter()method ?

如果您的数组实际上是一组 JQuery 对象,那么简单地使用.filter()方法怎么样?

purposeObjects.filter('[purpose="daily"]')

回答by feeeper

One more solution:

另一种解决方案:

function firstOrNull(array, expr) {
  for (var i = 0; i < array.length; i++) {
    if (expr(array[i]))
      return array[i];
    }
  return null;
}

Using: firstOrNull([{ a: 1, b: 2 }, { a: 3, b: 3 }], function(item) { return item.a === 3; });

使用: firstOrNull([{ a: 1, b: 2 }, { a: 3, b: 3 }], function(item) { return item.a === 3; });

This function don't executes for each element from the array (it's valuable for large arrays)

此函数不会为数组中的每个元素执行(它对大型数组很有价值)

回答by sanjay patel

I have created a util service for my angular application. It have two function which use very often.

我为我的 angular 应用程序创建了一个实用程序服务。它有两个经常使用的功能。

For example you have object.

例如你有对象。

First getting value from object recursively without throwing undefined error.

首先从对象递归获取值而不抛出未定义的错误。

{prop: { nestedProp1: {nestedProp2: somevalue}}}; get nestedProp2 2 without undefined checks.

{prop: {nestedProp1: {nestedProp2: somevalue}}}; 获得没有未定义检查的nestedProp2 2。

Second filter array on basis

基础上的第二个过滤器阵列

[{prop: { nestedProp1: {nestedProp2: somevalue1}}}, {prop: { nestedProp1: {nestedProp2: somevalue2}}}];

[{prop: {nestedProp1: {nestedProp2: somevalue1}}}, {prop: {nestedProp1: {nestedProp2: somevalue2}}}];

Find object from array with nestedProp2=somevalue2

使用nestedProp2=somevalue2 从数组中查找对象

app.service('UtilService', function(httpService) {
this.mapStringKeyVal = function(map, field) {
    var lastIdentifiedVal = null;
    var parentVal = map;
    field.split('.').forEach(function(val){
        if(parentVal[val]){
            lastIdentifiedVal = parentVal[val]; 
            parentVal = parentVal[val]; 
        }
    });
    return lastIdentifiedVal;
}


this.arrayPropFilter = function(array, field,value) {
    var lastIdentifiedVal = null;
    var mapStringKeyVal = this.mapStringKeyVal;
    array.forEach(function(arrayItem){
        var valueFound = mapStringKeyVal(arrayItem,field);
        if(!lastIdentifiedVal  && valueFound && valueFound==value){
            lastIdentifiedVal = arrayItem;
        }
    });
    return lastIdentifiedVal;
}});

For solution for current question. inject UtilService and call,

对于当前问题的解决方案。注入 UtilService 并调用,

UtilService.arrayPropFilter(purposeArray,'purpose','daily');

Or more advanced

或者更高级

UtilService.arrayPropFilter(purposeArray,'purpose.nestedProp1.nestedProp2','daily');

回答by user2688838

Javascript has a function just for that: Array.prototype.find. As example

Javascript 有一个函数:Array.prototype.find。例如

function isBigEnough(element) {
  return element >= 15;
}

[12, 5, 8, 130, 44].find(isBigEnough); // 130

It not difficult to extends the callback to a function. However this is not compatible with IE (and partially with Edge). For a full list look at the Browser Compatibility

将回调扩展到函数并不难。但是,这与 IE 不兼容(部分与 Edge 不兼容)。有关完整列表,请查看浏览器兼容性