0

In my node js application I have a variable (name) that contains an object's name; I need to assign that object to another object's property; I do this:

wrapElement[index].model = eval('model.' + name);

Jshint throws a well-documented warning for that (eval can be harmful); I know eval can be dangerous (but in this case i think I'm safe because 'name' is not an input from user) and bad for performance;

In this case do I really need to use eval() or there is a better way to accomplish this assignement?

--- UPDATE -----------------

As suggested below in comments, in this case I can simply do model[name] instead of eval(). The code of this application has been changed just today, keeping models in a separate node module and exported as 'model'; before models were defined in the same file:

Shop = {
    ...
}
Offer = {
    ...
}

And the assignement was:

wrapElement[index].model = eval(name);

In this case I was not able to write

something[name]

instead of using eval; In this case, should I include all the models (Shop, Offer, ...) into a wrappingObject in order to write wrappingObject[name] or I can access it with somethingElse[name]?

Cereal Killer
  • 3,387
  • 10
  • 48
  • 80
  • 6
    `wrapElement[index].model = model[name];` – danronmoon Jul 05 '14 at 00:28
  • 1
    I find it kind of amusing that you are using bracket notation and `eval` in a single expression. Do you know what `wrapElement[index]` actually does? – Felix Kling Jul 05 '14 at 00:32
  • You are right; this come from a recent change in the code (now model is exported from another module so I can do model[name] as suggested; just before the code was eval(name) so I was not able to write it like something[name]... – Cereal Killer Jul 05 '14 at 00:41
  • 1
    About your edit: Yes, you must use a wrapping object, or make them global so you can access them like `window[name]`. – Oriol Jul 05 '14 at 00:57

0 Answers0