【问题标题】:How to find object in array by property in javascript?如何在javascript中按属性查找数组中的对象?
【发布时间】:2021-06-25 22:14:21
【问题描述】:

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

输入对象:

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

【问题讨论】:

  • 不到一分钟就能解决您自己的问题!太棒了。
  • (别喝了,你看双...)
  • @wared 怎么了?这只是问答式的小技巧。
  • 问题是这是一个常见且相当微不足道的问题。您确认没有重复吗?
  • @BlueSkies 我发现了 dups,但顶级解决方案很糟糕。

标签: javascript arrays


【解决方案1】:

使用数组的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);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      相关资源
      最近更新 更多