dynamically call an object with sub objects
i am new to JS objects. I have such code
var foo = {
bar0: {
barr0: function() {//doo stuff}
barr1: function() {//doo stuff}
开发者_如何学C },
bar1: {
barr0: function() {//do stuff}
barr1: function() {//do stuff}
},
bar2: function() {//do stuff}
}
now i have this variable myVar
that holds the 'name' of any of the above in the format they would be called. like it can have bar0.barr1
or bar2
or mention to any other of the above objects. foo
will not be a part of myVar
because it is common for every call. One possible solution is to use eval
but i would like to avoid it if possible.
if the object was one dimensional i would have used foo[myVar]()
but this is now multidimensional and i hav no idea how should i call it.
You need to apply some scripting then.
// define our access string and copy a reference from foo into level
var myVar = 'bar0.barr1',
level = foo;
// split that access string into an Array (splitted by dots) and loop over it
myVar.split(/\./).forEach(function( prop ) {
// if the property name ("bar0", "barr1") is available in our target object
if( prop in level ) {
// overwrite our level variable with the new object property reference, so somekind "climb up" the latter if we're dealing with nested objects
level = level[ prop ];
}
});
// if we're done, check if level holds a function reference and if so, execute it.
if( typeof level === 'function' ) {
level();
}
There is no difference for multidimensional, just keep adding square brackets:
foo[myVar][myvar2]()
Edit: Never mind, misunderstood the question, which is ironic because I actually asked almost exactly this question!
In javascript how can I dynamically get a nested property of an object
精彩评论