Created
February 17, 2016 04:13
-
-
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'
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
/** | |
* 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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