Reputation: 55
So, I'm saving a obj like
var user = {"username": username, "info": info};
The thing is, this will be saved in an array, if I want to access ONLY that user how would I go about doing that? I'm usering array.push to add it to an array.
Upvotes: 0
Views: 38
Reputation: 16856
You can either use Array.find or Array.filter.
var users = [
{"username": "Bob", "info": "..."},
{"username": "Alice", "info": "..."}
];
function getUserByName( name ) {
var result = users.filter(function (u) {
return u.username === name;
});
return result.length ? result[0] : null;
}
console.log(getUserByName("Bob"));
console.log(getUserByName("Unkown"));
Note: The above snippet does not take duplicates usernames in account. It will return the first one it finds.
Upvotes: 3