Skip to content

Instantly share code, notes, and snippets.

@NickBolles
Created February 17, 2016 04:13
Show Gist options
  • Save NickBolles/caf94ff8c2b74e521551 to your computer and use it in GitHub Desktop.
Save NickBolles/caf94ff8c2b74e521551 to your computer and use it in GitHub Desktop.
Get a deep property of a javascript object. Accepts a property in the form 'foo.bar.deepProp.reallyDeepProp'
/**
* Get the value of a property that is nested in several objects given a string of properties in the form
* 'foo.bar.deepProp.reallyDeepProp' would return the value 'whew that was deep' from the object
* { foo: {
* bar: {
* deepProp:{
* reallyDeepProp: 'whew that was deep'
* }
* }
* }
*
* @param obj
* @param property
* @returns {*}
*/
function getDeepProperty(obj, property){
function isObject(value) { //Copied from Angular@1.4.9
return value !== null && typeof value === 'object';
}
var properties = property.split('.');
var tObj = obj;
//todo: catch error or throw it?
try{
//Loop through all but the last property
for (var i=0; i< properties.length-1;i++){
if (isObject(tObj[properties[i]])){
tObj = tObj[properties[i]];
}else{
throw new Error('\'' + properties[i] + '\' is not defined, or is not an object property of object ' + tObj);
}
}
//return the final property
return tObj[properties[properties.length-1]];
}catch(e){
console.log('Error: Trying to get property of a non-object value', e);
return null;
}
}
@NickBolles
Copy link
Author

Wow. Been a long time. Looking at this again I'd probably use properties.split(".").reduce((curObj,prop) => curObj[prop], óbj) (summarized) instead of a for loop with -1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment