Skip to content

Instantly share code, notes, and snippets.

@steverice
Created July 17, 2013 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steverice/6018000 to your computer and use it in GitHub Desktop.
Save steverice/6018000 to your computer and use it in GitHub Desktop.
Using strings with square brackets to access multidimensional properties of JS objects
/**
* 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