7

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.

kukkuz
  • 39,721
  • 6
  • 52
  • 88
Miguel Moura
  • 32,822
  • 74
  • 219
  • 400
  • Does this answer your question? [Check if object value exists within a Javascript array of objects and if not add a new object to array](https://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add) – Yogi Dec 24 '20 at 10:57

6 Answers6

12

Use array.some()

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

var status = memberships.some(function(el) {
  return (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.

Dan Philip
  • 3,904
  • 1
  • 14
  • 30
5

You can use Array#some method:

const memberExists = memberships.some(member => member.type === 'member');

Then, if(memberExists) ...

Dan Cantir
  • 2,767
  • 10
  • 24
1

You can use Array#some

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

console.log(memberships.some(m=>m.type==='member'));
Weedoze
  • 12,968
  • 1
  • 34
  • 57
1

You can also use find, which returns the first object if found else undefined.

let a = memberships.find(o => o.type === 'member');

if (a) {
  ...do something
}
FrankCamara
  • 348
  • 4
  • 9
1

I think this may help

let resultArray=memberships.filter(function(item) {
     return item["type"] === 'member';
});

the result array holds the data of the objects that has type member

sravanthi
  • 175
  • 1
  • 1
  • 15
0
    var memberships = [
        {
            "Name": "family_name",
            "Value": "Krishna"
        },
        {
            "Name": "email",
            "Value": "harikrishnar88@gmail.com"
        }
    ];

    let resultArray=memberships.filter(function(item) {
      return item["Name"] === 'email';
});
Nag Repala
  • 11
  • 3