oneday
oneday

Reputation: 1629

Cannot access object property using variable

I have an object that looks like this:

var set_1 = {
    id: 'set_1',
    nameofSet : 'English fruits',
    category: 'languages',
    cards : [
        {
            front : 'apple',
            back : 'jablko'
        },
        {
            front : 'orange',
            back : 'pomarancza'
        },
        {
            front : 'pear',
            back : 'gruszka'
        }
    ]
}

Now there's a function:

$('#chooseSet').on('click', '.setName', function() {
    var setName = this.getAttribute("data-set-name");
    editCards(setName);
});

This is the HTML:

<div class="setName" data-set-name="set_1">English fruits</div>

It gives the setName parameter to the editCards function that looks like this:

editCards(setName) {
    console.log(setName); // logs "set_1"
    console.log(setName.cards); // logs "undefined" - why?
    console.log(set_1.cards);  // logs the `cards` array from `set_1'.
    // code
}

It takes the setName parameter.

My question is - why doesn't the second console.log give me the cards' array as it does in the thirdconsole.log` example?

Upvotes: 0

Views: 82

Answers (1)

hazardous
hazardous

Reputation: 10837

Because any attribute's value is a string. So in your case data-set-name returns the string "set_1", which is not a reference to the variable set_1. If your set_1 variable is global, you should be able to do this instead -

console.log(window[setName].cards)

Upvotes: 4

Related Questions