如何在javascript中按属性查找数组中的对象? [英] How to find object in array by property in javascript?

查看:1428
本文介绍了如何在javascript中按属性查找数组中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存在包含大量对象的数组。必需找到这个阵列由属性中一个或多个对象

Exist an array with a lot of objects. Required to find an object or objects in this array by property.

输入OBJ:

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



输出结果:(搜索 开始 与值4)

Output result: (search for "start" with value 4)

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


推荐答案

_findItemByValue(Obj,start,4);

_findItemByValue(Obj, "start", 4);

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

与IE6,IE7,IE8以外的所有产品兼容,但存在 polyfill

Compatible with all except IE6, IE7, IE8, but exist 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;
  };
}

这篇关于如何在javascript中按属性查找数组中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆