9

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.

1

6 Answers 6

15

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.

Sign up to request clarification or add additional context in comments.

Comments

7

You can use Array#some method:

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

Then, if(memberExists) ...

Comments

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

Comments

1

You can use Array#some

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

console.log(memberships.some(m=>m.type==='member'));

2 Comments

Array.prototype.some() would likely be faster/cheaper since it doesn't need to process the whole array.
@DavidThomas That's true
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
}

Comments

0
    var memberships = [
        {
            "Name": "family_name",
            "Value": "Krishna"
        },
        {
            "Name": "email",
            "Value": "[email protected]"
        }
    ];

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.