0

I have an array that looks like this:

var myArray = [
  {'id' : 1, 'name' : 'test1'},
  {'id' : 2, 'name' : 'test2'},
  {'id' : 3, 'name' : 'test3'}
];

Then I have a variable that contains some id:

var someId = 2;

How can I check if myArray contains an Object, who's id is equal to someId?

  • 1
    Possible duplicate of [Find object by id in an array of JavaScript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – JJJ Jan 13 '16 at 15:47
  • Do you just want to know it is there or do you want the value? – epascarello Jan 13 '16 at 15:48

3 Answers3

5

You can use the .some() method:

var isThere = myArray.some(function(element) {
  return element.id == someId;
});

The .some() method returns a boolean true if the callback returns true for some element. The iteration stops as soon as that happens.

If you want the element in the array and not just a yes/no answer, you can pass the same kind of callback to .find():

var theElement = myArray.find(function(element) {
  return element.id == someId;
});

When that callback returns true, the iteration stops and .find() returns the element itself. If none is found, it returns undefined.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • So much nicer than a `for` loop or `filter` etc, EDIT: Note `.find()` has no IE support according to MDN. – ste2425 Jan 13 '16 at 15:51
  • 1
    For those supporting IE 8, `.some()` is not supported. It is IE 9+. – John Washam Jan 13 '16 at 22:16
  • 1
    @JohnWasham true - [MDN has a polyfill for old browsers though.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some#Polyfill) – Pointy Jan 14 '16 at 04:57
0

You can try following

var filteredArray = myArray.filter(function(item) {
    return item.id == someId

});

if(filteredArray.length > 0) {
   console.log("Found");
}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

Vanilla JS:

var myArray = [
  {'id' : 1, 'name' : 'test1'},
  {'id' : 2, 'name' : 'test2'},
  {'id' : 3, 'name' : 'test3'}
];

function findby(arr, key, val){
    for(var i=0; i<arr.length; i++){
       if(arr[i][key] === val){
           return arr[i];
        }
    }
    return null;
}

var found = findby(myArray, "id", 2);
alert(found.name);
bob
  • 7,539
  • 2
  • 46
  • 42