1
<div id="bach">Bach</div>
<div id="show">about composer</div>

$(window).load(function(){    
  bach = {"bdate": 1685, "bplace": "Eisenach, Germany"}

  $("div").click(function(){
    $("#show").text(this.id['bdate']); // This is the problem 
  });       
});

Hi, I'm currently trying to create a way to dynamically access the bach object. If I use bach instead of this.id everything works fine. Somehow I need to find a way to convert this.id to something that I can use in the context of accessing a property in the bach object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators

Javascript: interpret string as object reference?

Here are a couple websites that my research led me to. Either I'm not understanding what they're saying or they are not exactly related to my problem.

Thanks

Community
  • 1
  • 1

1 Answers1

2

As you're clearly in the window scope, you can use bracket notation

$(window).load(function(){    
  bach = {"bdate": 1685, "bplace": "Eisenach, Germany"}

  $("div").click(function(){
    $("#show").text(window[this.id]['bdate']);
  });       
});

wether it's a good idea or not is another matter

or as suggested by Rocket Hazmat

var obj = { bach : {"bdate": 1685, "bplace": "Eisenach, Germany"}};

$(window).load(function(){    
    $("div").click(function(){
        $("#show").text(obj[this.id]['bdate']);
    });       
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • I'd suggest putting `bach` into its own object: `var obj = {bach: {...}};` Then you can do `obj[this.id].bdate` :-) – gen_Eric Jan 09 '14 at 20:44
  • 1
    @RocketHazmat - was just thinking about that, and it's how I would have done it, so I've added it to the answer. Thanks – adeneo Jan 09 '14 at 20:45