1

i am new to JS objects. I have such code

var foo = {
    bar0: {
        barr0: function() {//doo stuff}
        barr1: function() {//doo stuff}
    },
    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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Achshar
  • 5,153
  • 8
  • 40
  • 70

2 Answers2

2

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();
}
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • can you please add some comments describing what the above code does? and should i wrap this into a function? since i will need to call it multiple times.. – Achshar Aug 09 '11 at 10:06
  • how will this work with the third dimension and beyond? from what i understand, it overrides the `level` var with each additional 'dimension' so in `bar0.barr0.barrr0` `level` will be `barr0['barrr0']` .. but it has to be `bar[barr0][barrr0]` right? – Achshar Aug 09 '11 at 10:21
  • [Not all browsers](http://stackoverflow.com/questions/156696/which-web-browsers-natively-support-array-foreach) know about forEach. – Catherine Aug 09 '11 at 10:30
  • oh okiee.. never mind.. it replaced `level` with what `level` was before + new prop. Thanks a ton.. it works like a charm :D – Achshar Aug 09 '11 at 10:31
  • @whitequark no worries.. it is for a chrome app which requires minimum version 13 ;) – Achshar Aug 09 '11 at 10:32
0

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

Community
  • 1
  • 1
Ariel
  • 25,995
  • 5
  • 59
  • 69