jenswirf
jenswirf

Reputation: 7317

Why doesn't this object reference work?

I'm trying to populate this list with strings from the object data. It comes out as 'undefined'. It's the reference to the data object that doesn't work. Why?

JS

data = [
        {"q":"How much?", "ac":"20%", "a1": "1%", "a2": "10%", "a3": "5%"},
        {"q":"What", "ac":"Ball", "a1": "Stone", "a2": "Bierd", "a3": "Carl"},
        {"q":"When?", "ac":"1999", "a1": "2000", "a2": "2001", "a3": "2002"}
        ];      

var q=0

window.onload = function() {
    var ids =['a','b','c','d'];
    var ans =['a1','a2','a3','ac'];
    for (var j=0; j < ids.length; j++) {
    var a = ans[j];
    document.getElementsByClassName(ids[j])[0].innerHTML = data[q].a; //[<-- PROBLEM HERE]

};
}

HTML

<ul class="answers_quiz">
<li class="a"></li>
<li class="b"></li>
<li class="c"></li>
<li class="d"></li>
</ul>

Upvotes: 1

Views: 55

Answers (1)

James Allardice
James Allardice

Reputation: 165971

You need to use the square bracket syntax rather than the dot syntax to use a variable as a property accessor:

element.innerHTML = data[q][a];

The dot syntax looks for a property named "a" in data[q]. Since there is no such thing, it returns undefined. When you use the array notation, it looks for a property named whatever a contains.

For example, on the first iteration, when a === "a1", data[q].a1 is equivalent to data[q][a].

Upvotes: 4

Related Questions