0

I am attempting to access an object with a dynamic key that is obtained from a list item on click. Each list item has a class that matches a key within the object. For some reason is get "undefined". Here is the fiddle http://jsfiddle.net/defmetalhead/sFLGA/

 $(function() {
    var a = 1;
    var b = 2;
    var c = 3;
    var d = 4;
    var e = 5;
    $('.menu li').on('click', function() {
        var liClass = $(this).attr('class');
        console.log(liClass);
        var someObject = {
            "a": a,
            "b": b,
            "c": c,
            "d": d,
            "e": e
        }
        console.log(someObject.a);        //THIS WORKS FINE
        console.log(someObject.liClass); //WHY DOESN'T THIS WORK
    });
});

Here is the HTML

<ul class="menu">
    <li class="a">First</li>
    <li class="b">Second</li>
    <li class="c">Third</li>
    <li class="d">Fourth</li>
    <li class="e">Fifth</li>
</ul>
David Aguirre
  • 1,382
  • 4
  • 15
  • 29
  • possible duplicate of [JavaScript object: access variable property by name as string](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string) – Felix Kling Mar 17 '14 at 23:27

2 Answers2

4

liClass is not property of someObject. Do a plain console.log(liClass);

nikos.svnk
  • 1,375
  • 1
  • 13
  • 24
  • liClass can be equal to "a" for instance. if the user clicks the first list item. So clicking the first list item should result in someObject.a – David Aguirre Mar 17 '14 at 22:54
1

You have to do someObject[liClass]. someObject.liClass really means someObject["liClass"].

hacatu
  • 638
  • 6
  • 15