0

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.

3
  • ?? If the object is in an array, like var a = [user]; then a[0] gives you a reference to the object. Commented Aug 9, 2016 at 14:14
  • What do you mean "only that user"? If it's in an array, you can get it by the index like this users[index]. Commented Aug 9, 2016 at 14:17
  • Needs more explanation. You can filter arrays as well; eg. if you only have a username and not the index of that object in the array. Commented Aug 9, 2016 at 14:22

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.