-
-
Save jasonrhodes/2321581 to your computer and use it in GitHub Desktop.
| /** | |
| * A function to take a string written in dot notation style, and use it to | |
| * find a nested object property inside of an object. | |
| * | |
| * Useful in a plugin or module that accepts a JSON array of objects, but | |
| * you want to let the user specify where to find various bits of data | |
| * inside of each custom object instead of forcing a standardized | |
| * property list. | |
| * | |
| * @param String nested A dot notation style parameter reference (ie "urls.small") | |
| * @param Object object (optional) The object to search | |
| * | |
| * @return the value of the property in question | |
| */ | |
| function getProperty( propertyName, object ) { | |
| var parts = propertyName.split( "." ), | |
| length = parts.length, | |
| i, | |
| property = object || this; | |
| for ( i = 0; i < length; i++ ) { | |
| property = property[parts[i]]; | |
| } | |
| return property; | |
| } |
cool. I like it, thanks.
Nice script dude
That page came up in search, but there's a lovely answer here...
http://stackoverflow.com/questions/8051975/access-object-child-properties-using-a-dot-notation-string
var myData = {
someProperty: {
deeperProperty: 'thing'
}
},
myVal;
function getDescendantProp (obj, desc) {
var arr = desc.split('.');
while (arr.length && (obj = obj[arr.shift()]));
return obj;
}
myVal = getDescendantProp(myData, 'someProperty.deeperProperty');working perfectly.
A functional answer might be (es2015 just because):
const getDescendantProp = (obj, path) => (
path.split('.').reduce((acc, part) => acc && acc[part], obj)
);Does anyone know how i'd do this without knowing the object. Say if I wanted to simply convert the dot notation string to an object reference (as I don't need to return the value).
Masterful function. Just what I needed :) 🥇
This is what i needed :) thank you
@jasonrhodes Awesome little gem here, thank you!
Just wanted to point out that this snippet fails if the property doesn't exist, e.g.:
getProperty('a.b.c', {a:{b:{}}});
Would there be any complications if I do a try ... catch in the loop and return undefined if it throws?
EDIT: just noticed the post by @doublejosh , seems like there's a simpler solution without involving try/catch. cheers!
hi dudes
is there anybody help me about angular 6?
@laxa88 Hi
I tried 10 other examples before this that all failed miserably, yours worked like a charm, thanks!
How can I get this working for something like obj->geometry[6]->obs[3]->latitude ?
Would anyone know how to do this to handle array as well? like being able to do
myVal = getDescendantProp(myData, 'someProperty.deeperProperty[0].evendeeperproperty');
A functional answer might be (es2015 just because):
const getDescendantProp = (obj, path) => ( path.split('.').reduce((acc, part) => acc && acc[part], obj) );
Damn man, it doesn't even error if the path is not valid (no optional chaining needed), L33T. Thanks ! ❤️
Usage example: