小编典典

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

javascript

存在一个包含许多对象的数组。通过属性在此数组中查找一个或多个对象所必需。

输入obj:

  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"}
  ];

阅读 423

收藏
2020-05-01

共1个答案

小编典典

_findItemByValue(Obj,“开始”,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;
  };
}
2020-05-01