quackkkk
quackkkk

Reputation: 149

How to avoid eval when accessing object properties?

I've read quite a lot but I can't figure out the following:

var eventCity = [
    {date: 'Apr 11 2017', type: 'alpha'},
    {date: 'Apr 26 2017', type: 'beta'}
];

var currentCity = 'eventCity';  // this is generated dynamically

var aDate = eval(currentCity)[0].date;

How to avoid the use of eval() maintaining the same result ( aDate = 'Apr 11 2017' ) ?

Upvotes: 1

Views: 35

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

Why not use an object and take the dynamic value as key?

var object = {
        eventCity: [
            { date: 'Apr 11 2017', type: 'alpha' },
            { date: 'Apr 26 2017', type: 'beta' }
        ]
    },
    currentCity = 'eventCity',  // this is generated dynamically
    aDate = object[currentCity][0].date;

Upvotes: 1

MStoner
MStoner

Reputation: 750

var options = []

options['eventCity']=[ {date: 'Apr 11 2017', type: 'alpha'}, {date: 'Apr 26 2017', type: 'beta'} ];

Upvotes: 0

Related Questions