Reputation: 33
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
Reputation: 1294
Try it like this:
var empdept = 'financialDept';
var settings = {};
settings[emdept] = [{
'name' : 'bob',
'sname' : 'the builder',
'age' : '8',
'req' : 'yes'
}];
Upvotes: 1
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