Skip to content

Instantly share code, notes, and snippets.

@cdmckay
Created July 15, 2015 03:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cdmckay/6ac36defdc01d39080fa to your computer and use it in GitHub Desktop.
Save cdmckay/6ac36defdc01d39080fa to your computer and use it in GitHub Desktop.
A simple "elvis" operator in JavaScript
function elvis(object, path) {
return path ? path.split('.').reduce(function (value, key) {
return value && value[key];
}, object) : object;
}
// Example
var o = { a: { b: 1, c: 2 }, d: 3 };
elvis(o, 'a');
// = { b: 1, c: 2 }
elvis(o, 'a.b');
// = 1
elvis(o);
// = { a: { b: 1, c: 2 }, d: 3 }
elvis(o, 'x');
// = undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment