Skip to content

Instantly share code, notes, and snippets.

@BrianHicks
Last active December 15, 2015 00:19
Show Gist options
  • Save BrianHicks/5172186 to your computer and use it in GitHub Desktop.
Save BrianHicks/5172186 to your computer and use it in GitHub Desktop.
// say you have the following object:
var friends = {
bob: {name: "Bob Robertson", nickname: "Bob the Terrible"},
jim: {name: "Jim Jameson", nickname: "Jim the Magnificent"},
bill: {name: "Bill Williamson", nickname: "Doodles"},
}
// So if you want to get Bob's nickname, you could access it like so:
console.log(friends.bob.nickname); // prints "Bob the Terrible"
// but say you just have Bill's name in a variable, and you need to look it up.
var someone = "bill";
// you can't do this, the key "someone" doesn't exist in the object.
console.log(friends.someone); // returns undefined, since it isn't defined
// so instead, you use the other object access form: brackets!
console.log(friends[someone].nickname); // prints "Doodles"
// this goes back to how variables work:
var x = 1;
var y = 2;
console.log(x + y); // prints 3
friends = {
"bob": {"name": "Bob Robertson", "nickname": "Bob the Terrible"},
"jim": {"name": "Jim Jameson", "nickname": "Jim the Magnificient"},
"bill": {"name": "Bill Williamson", "nickname": "Doodles"},
}
# blah blah blah
print friends["bob"]["nickname"] # prints "Bob the Terrible"
# blah? Blah.
name = "bill"
# nope!
print friends["name"] # Raises KeyError
# yep!
print friends[name]["nickname"]
# variables!
var x, y = 1, 2
print x + y # prints 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment