streetlight
streetlight

Reputation: 5968

Accessing JS object with variable

I'm having trouble accessing a particular object using a variable in javascript. Here's the code I'm working with:

global_grouplist = getTenantGroupList();
console.log(global_grouplist)
var currentgroup = getSelectedGroupName();
console.log(currentgroup)
console.log(global_grouplist.currentgroup);

'global_grouplist' returns a large array of objects, and I want to get a particular value from there. If I take the value that currentgroup will equal, and run it like this:

console.log(global_grouplist.actualvalue)

It gives me what I want. However, when I do this.

var currentgroup = actualvalue
console.log(global_grouplist.currentgroup)

This is the getTenantGroupList() function:

function getTenantGroupList(){
    return jQuery.parseJSON($.ajax({
            url: 'tenantgrouplist.json',
            dataType: 'json',
            async: false
    }).responseText);
}

And here is the getSelectedGroupName function:

function getSelectedGroupName(){
        var retval = null;
        $('#grouplist li a').each(function(){
            if($(this).parent().hasClass('group-selected'))
                retval=$(this).html();
        });
        return retval;
    }

It does not work. Is there something fundamental I'm missing here? If you need more information, please let me know!

Upvotes: 0

Views: 97

Answers (2)

Sirko
Sirko

Reputation: 74036

With this row

var currentgroup = actualvalue

you are giving the current value of actualvalue to currentgroup and do not make both elements point towards the same property!

If you want to use currentgroup as a placeholder for a variable, you should use this instead:

var currentgroup = 'actualvalue';
console.log(global_grouplist[currentgroup]);

That way you assign the name of the desired property as a string to currentgroup and use the bracket notation to access the respective property of your object.

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

To access the properties in this manner you need to use array notation. Try this:

var currentgroup = getSelectedGroupName(); // Returns a string like: 'actualvalue';
console.log(global_grouplist[currentgroup])

Upvotes: 1

Related Questions