-
-
Save brynner/ac5f950d41e25e47684fbd873429e1fe to your computer and use it in GitHub Desktop.
Get a nested object property by passing a dot notation string as the property name
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
/** | |
* 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; | |
} |
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 a nested object property by passing a dot notation string as the property name | |
*/ | |
// Use this | |
function getDescendantProp(obj, desc) { | |
var arr = desc.split('.'); | |
while (arr.length && (obj = obj[arr.shift()])); | |
return obj; | |
} | |
// Or this | |
function getProperty(object, propertyName) { | |
var parts = propertyName.split( "." ), | |
length = parts.length, | |
i, | |
property = object || this; | |
for (i = 0; i < length; i++) { | |
property = property[parts[i]]; | |
} | |
return property; | |
} | |
// i18n with params | |
function text(name, params = {}) { | |
var i18n = | |
{ | |
"about": "About", | |
"account": { | |
"welcome": "Welcome "+params.username, | |
"info": "Something here." | |
} | |
}; | |
var obj = getDescendantProp(i18n, name); | |
//var obj = getProperty(i18n, name); | |
return obj; | |
} | |
var result = text('account.welcome', {username: 'Brynner'}); | |
document.querySelector('#result').innerHTML = result; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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