简体   繁体   English

如何在 javascript 中按属性在数组中查找 object?

[英]How to find object in array by property in javascript?

Exist an array with a lot of objects.存在一个包含很多对象的数组。 Required to find an object or objects in this array by property.需要按属性在此数组中查找 object 或对象。

Input obj:输入对象:

  var Obj = [
    {"start": 0, "length": 3, "style": "text"},
    {"start": 4, "length": 2, "style": "operator"},
    {"start": 4, "length": 3, "style": "error"}
  ];

Output result: (search for "start" with value 4) Output 结果:(搜索值为 4 的“开始”)

  var result = [
    {"start": 4, "length": 2, "style": "operator"},
    {"start": 4, "length": 3, "style": "error"}
  ];

Use filter function of array使用数组的过滤功能

 var Obj = [ {"start": 0, "length": 3, "style": "text"}, {"start": 4, "length": 2, "style": "operator"}, {"start": 4, "length": 3, "style": "error"} ]; var result = Obj.filter(x => x.start === 4); console.log(result);

_findItemByValue(Obj, "start", 4); _findItemByValue(Obj, "开始", 4);

var _findItemByValue = function(obj, prop, value) {
  return obj.filter(function(item) {
    return (item[prop] === value);
  });
}

Compatible with all except IE6, IE7, IE8, but exist polyfill .兼容除 IE6、IE7、IE8 之外的所有版本,但存在polyfill

if (!Array.prototype.filter) {
  Array.prototype.filter = function (fn, context) {
    var i,
        value,
        result = [],
        length;

        if (!this || typeof fn !== 'function' || (fn instanceof RegExp)) {
          throw new TypeError();
        }

        length = this.length;

        for (i = 0; i < length; i++) {
          if (this.hasOwnProperty(i)) {
            value = this[i];
            if (fn.call(context, value, i, this)) {
              result.push(value);
            }
          }
        }
    return result;
  };
}

We can create an util function like below which works for filtering the array based on any key using the filter method of Array.我们可以创建一个 util function 如下所示,它用于使用 Array 的过滤方法基于任何键过滤数组。

function filterObjects(objArr,key,value){      
      return objArr.filter(obj => obj[key]===value);    
}
    
filterObjects(objArr,'name','Email');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM