Skip to content

Instantly share code, notes, and snippets.

@dgoguerra
Created May 10, 2015 18:27
Show Gist options
  • Save dgoguerra/313d783087575b3744cd to your computer and use it in GitHub Desktop.
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)
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