I have an array of objects in my Javascript/React app:
[
{type: 'TypeOne'}
{type: 'TypeFive'}
{type: 'TypeTen'}
]
How to return a boolean true
if the array contains an object with key/value type: 'TypeTen'
?
I have an array of objects in my Javascript/React app:
[
{type: 'TypeOne'}
{type: 'TypeFive'}
{type: 'TypeTen'}
]
How to return a boolean true
if the array contains an object with key/value type: 'TypeTen'
?
You can use the Array.prototype.some() method along with an arrow function. Here's an example:
function checkTypeExists(targetType) {
return arr.some(obj => obj.type === targetType);
}
So there are two ways to do this:
This way can be clearer and allow beginners to read your code easily. It's also cleaner and slightly more efficient:
const source = [ { 'type': 'TypeOne' }, ... ]
for (const obj of source)
if (obj.type == 'TypeTen')
return true
return false
This way is better (in my opinion) because of brevity. It's a one-liner and still easy enough to read and understand. It will be slightly less efficient in larger arrays since it has to invoke a callback arr.length
times.
arr.some(obj => obj.type == 'TypeTen')