Skip to content

Instantly share code, notes, and snippets.

@colintoh
Last active August 29, 2015 14:26
Show Gist options
  • Save colintoh/9c3a16f916e9ab370234 to your computer and use it in GitHub Desktop.
Save colintoh/9c3a16f916e9ab370234 to your computer and use it in GitHub Desktop.
var person = {
"name": "colin",
"pets": [{"name": "Bailey"}, {"name": "Molly"}]
};
_.get(person, 'pets[1].name'); // Molly
_.set(person, 'pets[1].name', 'Ginger');
_.get(person, 'pets[1].name') // Ginger
// Using dot notation to access
person.pets[0].name // Bailey
person.pets[2].name; // Results in "TypeError: Cannot set property 'age' of undefined"
// Using _.get
_.get(person, 'pets[2].name'); // undefined
// Using dot notation to access and set
person.pets[2].name = 'Buddy'; // Results in "TypeError: Cannot set property 'age' of undefined"
// Using _.set to access and set
_.set(person, 'pets[2].name', 'Buddy');
_.get(person, 'pets[2].name'); // Buddy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment