NiLL
NiLL

Reputation: 13853

How to find object in array by property in javascript?

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

Input obj:

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

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

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

Upvotes: 2

Views: 6664

Answers (3)

yashwanth numburi
yashwanth numburi

Reputation: 64

We can create an util function like below which works for filtering the array based on any key using the filter method of Array.

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

Upvotes: 0

Vivek Jain
Vivek Jain

Reputation: 2864

Use filter function of array

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

Upvotes: 4

NiLL
NiLL

Reputation: 13853

_findItemByValue(Obj, "start", 4);

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

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

Upvotes: 0

Related Questions