Created
May 10, 2015 18:27
-
-
Save dgoguerra/313d783087575b3744cd to your computer and use it in GitHub Desktop.
Access a nested object property using a string with Lodash / Underscore (or another implementation of the reduce() function)
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 getObjProperty(containerObj, str, defaultValueArg) { | |
var defaultValue = typeof defaultValueArg !== 'undefined' ? defaultValueArg : null; | |
try { | |
return _(str.split('.')).reduce(function(obj, key) { | |
return obj[key]; | |
}, containerObj); | |
} catch (e) { | |
return defaultValue; | |
} | |
} | |
// Example: | |
var elem = { | |
product: { | |
brand: { id: "123", name: "Product Brand" } | |
} | |
}; | |
getObjProperty(elem, "product.brand.name"); | |
// returns: "Product Brand" | |
getObjProperty(elem, "product.manufacturer.name", "Default manufacturer"); | |
// not found, returns: "Default manufacturer" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment