Access Enum in javascript from JSON object -


i have json object came rest service. on server , on front end i've declared constants have same name complement each other.

they share data, each constant has things relevant either front end or end. on front end, preferred way map front end constant end constant?

on backend, buildingtype enum. in json object below, first field buildingtype

{buildingtype: "cannon", hp: 100, level: 1, location: object, name: "cannon"} 

here javascript code map front end version of constant

    var imagemetadata = eval("clashalytics.images." + building.buildingtype);     // in case, eval same      var imagemetadata = clashalytics.images.cannon; 

i'm java developer primarily, fyi.

use array-like notation.

eval("clashalytics.images." + building.buildingtype) 

is equivalent

clashalytics.images[building.buildingtype] 

you define getter so

function getconst(target, path) {   return target[path]; } 

and use it

getconst(clashalytics.images, building.buildingtype) 

don't use eval needlessly!

eval() dangerous function, executes code it's passed privileges of caller. if run eval() string affected malicious party, may end running malicious code on user's machine permissions of webpage / extension. more importantly, third party code can see scope in eval() invoked, can lead possible attacks in ways similar function not susceptible.

eval() slower alternatives, since has invoke js interpreter, while many other constructs optimized modern js engines.

https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/eval


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -