Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if one element exists in an array of objects

I have the following array of objects:

var memberships = [
  {
    id: 1,
    type: 'guest'
  },
  {
    id: 2,
    type: 'member'
  }
];

How can I verify if such an array has at least one element with type 'member'?

Note that the array can also have no elements.

like image 311
Miguel Moura Avatar asked Apr 20 '17 12:04

Miguel Moura


1 Answers

Use array.some()

var memberships = [{
    id: 1,
    type: 'guest'
  },
  {
    id: 2,
    type: 'member'
  }
];

var status = memberships.some(function(el) {
  return (el.type === 'member');
});

/*
  // Simplified format using arrow functions
  var status = memberships.some(el => el.type === 'member')
*/
console.log(status);

Array.some()

Array.some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value. If such an element is found, some() immediately returns true. Otherwise, some() returns false.

like image 159
Dan Philip Avatar answered Sep 22 '22 19:09

Dan Philip