Last active
August 29, 2015 13:57
-
-
Save jeff-mccoy/9700352 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Performs nested property lookups without eval or switch(e.length), removed try {} catch(){} | |
* due to performance considerations. Uses a short-circuit for invalid properties & returns false. | |
* | |
* data = { | |
* a1: { b1: "hello" }, | |
* a2: { b2: { c2: "world" } } | |
* } | |
* | |
* deepRead(data, "a1.b1") => "hello" | |
* | |
* deepRead(data, "a2.b2.c2") => "world" | |
* | |
* deepRead(data, "a1.b2") => false | |
* | |
* deepRead(data, "a1.b2.c2.any.random.number.of.non-existant.properties") => false | |
* | |
* @param {object} data - The collection to iterate over | |
* @param {string} expression - The string expression to evaluate | |
* | |
* @return {various | boolean} retVal - Returns the found property or false if not found | |
* | |
*/ | |
var deepRead = function (data, expression) { | |
// Cache a copy of the split expression, then set to exp | |
var exp = expression.split('.'), retVal; | |
// Recursively read the object using a do-while loop, uses short-circuit for invalid properties | |
do { | |
retVal = (retVal || data)[exp.shift()] || false; | |
} while (retVal !== false && exp.length); | |
// Return our retVal or false if not found | |
return retVal || false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment