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 ;-)
There are many ways to implement that, for example, here are four ES6 methods for that:
some() will return true or false, depending on the condition. It tests, does at list one element fits the conditionfind() will return an item itself (the first matched item), if the condition evaluates to true, and undefined if it evaluates to false.findIndex() will return an index of the item (the first matched index), if the condition evaluates to true, and -1 if it evaluates to falsefilter() 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)
users.find(user => user.name ==='Mike')
or
users.filter(user => user.name ==='Mike').length !== 0
or
users.map(user => user.name).includes('Mike')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With