如何在javascript中按属性查找数组中的对象

How to find object in array by property in javascript?

本文关键字:查找 数组 对象 属性 javascript      更新时间:2023-10-09

存在一个包含大量对象的数组。需要按属性查找此数组中的一个或多个对象。

输入对象:

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

输出结果:(搜索值为4的"开始")

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

使用阵列的过滤功能

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);

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

兼容除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;
  };
}

我们可以创建一个如下的util函数,该函数使用array的filter方法根据任何键过滤数组。

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