Created
July 17, 2013 05:57
-
-
Save steverice/6018000 to your computer and use it in GitHub Desktop.
Using strings with square brackets to access multidimensional properties of JS objects
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
/** | |
* Example: incoming property name (e.g. from PHP) has square brackets, e.g. names[0][1] | |
* var property = names[0][1]; | |
* var value = { | |
* names: [ | |
* ['some', 'data', 'here'] | |
* ] | |
* } | |
* result: value == 'some' | |
* | |
* A simple for loop splits the property name into its component parts and evaluates them one level at a time | |
*/ | |
var propertyParts = property.split('['); | |
for (var i=0; i<propertyParts.length; i++) { | |
value = value[propertyParts[i].replace(']','')]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment