简体   繁体   中英

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

Try

 settings[empDept] = { // etc

Try it like this:

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

settings[emdept] = [{
    'name'       : 'bob',
    'sname'      : 'the builder',
    'age'        : '8',
    'req'        : 'yes'
}];
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM