Tman
Tman

Reputation: 33

to generate object name dynamically

im trying to create my object name dynamically. below is code

var empdept = 'financialDept';

                var settings = { empdept :[{
                'name'       : 'bob',
                'sname'      : 'the builder',
                'age'        : '8',
                'req'        : 'yes'}]
            };

so if i want to show the age like this alert(settings.financialDept.age); is not working, but if i have the above snippet code like this

var settings = { 'financialDept' :[{

                'name'       : 'bob',
                'sname'      : 'the builder',
                'age'        : '8',
                'req'        : 'yes'}]
            };

and now if i want to show the age like this alert(settings.financialDept.age);. this one works. please really need help to do it dynamically. any help really appreciated. thanks

Upvotes: 0

Views: 154

Answers (3)

chris_b
chris_b

Reputation: 1294

Try it like this:

var empdept  = 'financialDept';
var settings = {};

settings[emdept] = [{
    'name'       : 'bob',
    'sname'      : 'the builder',
    'age'        : '8',
    'req'        : 'yes'
}];

Upvotes: 1

stewe
stewe

Reputation: 42654

var o={key:value};

here only value may be a variable, not key.

what you can do is this:

var empdept = 'financialDept';
var settings = {};
settings[empdept]={name:'bob',sname:'the builder',age:'8',req:'yes'};
alert(settings.financialDept.age);

I removed the extra array so you can access the value as you described (not settings.financialDept[0].age as in your example)

Upvotes: 0

djna
djna

Reputation: 55957

Try

 settings[empDept] = { // etc

Upvotes: 2

Related Questions