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

时间:2013-11-25 14:47:40

标签: javascript arrays

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

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

2 个答案:

答案 0 :(得分:0)

_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;
  };
}

答案 1 :(得分:0)

使用数组的filter函数

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