Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object with specific value in array [duplicate]

I have an array of objects like this:

"users": [
   {
     "type": "User",
     "userId": "5b774905c2b2ac0f33ac4cc7",
     "name": "Mike"
   },
   {
     "type": "User",
     "userId": "5b77490f3084460f2986bd25",
     "name": "Pater"
   }
]

Now, I would like to check if my array contains an object with the name "Mike".

How do I go about this in javascript?

I am thinking something like this, but not sure how:

if ( "Mike" in users ) {
   // Do something...
}

Hoping for help on this, and thanks in advance ;-)

like image 857
Mansa Avatar asked May 11 '26 06:05

Mansa


2 Answers

There are many ways to implement that, for example, here are four ES6 methods for that:

  1. some() will return true or false, depending on the condition. It tests, does at list one element fits the condition
  2. find() will return an item itself (the first matched item), if the condition evaluates to true, and undefined if it evaluates to false.
  3. findIndex() will return an index of the item (the first matched index), if the condition evaluates to true, and -1 if it evaluates to false
  4. filter() will create a new array with all items, which fit the condition (otherwise it returnes an empty array)

const users = [
   {
     "type": "User",
     "userId": "5b774905c2b2ac0f33ac4cc7",
     "name": "Mike"
   },
   {
     "type": "User",
     "userId": "5b77490f3084460f2986bd25",
     "name": "Pater"
   }
];

const someObject = users.some(item => item.name === 'Mike');
const targetObject = users.find(item => item.name === 'Mike');
const targetIndex = users.findIndex(item => item.name === 'Mike');
const filteredObjects = users.filter(item => item.name === 'Mike');

console.log('someObject:', someObject)
console.log('targetObject:', targetObject)
console.log('targetIndex:', targetIndex)
console.log('filteredObjects:', filteredObjects)
like image 100
Commercial Suicide Avatar answered May 13 '26 21:05

Commercial Suicide


users.find(user => user.name ==='Mike')

or

users.filter(user => user.name ==='Mike').length !== 0

or

users.map(user => user.name).includes('Mike')

like image 24
ashish singh Avatar answered May 13 '26 20:05

ashish singh