Created
July 15, 2015 03:46
-
-
Save cdmckay/6ac36defdc01d39080fa to your computer and use it in GitHub Desktop.
A simple "elvis" operator in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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