I have an object called collection, and I want to test to see if justin is part of this collection.
collection = { 0:{screen_name:"justin"},1:{screen_name:"barry"}}
I'm trying to discover the most efficient method, to pass in a name to function called present_user(user)
, to see if the user is part of the collection and I'm kind of stumped.
So my collection is built up of objects 0, 1, n+1. I'm trying to iterate through this collection. So far I only test [0]
function present_user(user) {
collection[0]["screen_name"] == user -> return true in the case of "justin"
}
How can I iterate over all values of this collection, and return true if the user_name "justin" is passed into a function?
There are two methods to iterate over an object which are discussed below: Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.
There are three common ways to iterate through a Collection in Java using either while(), for() or for-each(). While each technique will produce more or less the same results, the for-each construct is the most elegant and easy to read and write.
Difference between for...of and for...inThe for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.
Your collection is an object and not an array, so this would be a way to do it:
var present_user = function(user){
for (var k in collection) {
if (collection[k]['screen_name'] == user) return true;
}
return false;
};
If your outer object keys are all numbers, you should be using an array instead:
var collection = [{screen_name:"justin"}, {screen_name:"barry"}];
Then iterate with:
function present_user(user) {
for(var i=0; i < collection.length; i++) {
if(collection[i].screen_name === user) return true;
}
}
You could loop the object collection too (with for..in
, see mVChr's answer), but in this case it looks like you really should be using an array.
You could also turn a collection or object into an array, so that you could use array methods to iterate:
Object.values(collectionOrObject);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
This especially comes in handy when you use the native javascript dom selectors like:
document.getElementsByClassName('someClass');
Which returns a collection
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