-6

I'd like to do something like this:

function someFunction(expression){
    eval(expression) = 1234;
}

Or in other words, to pass a certain field name as an argument and then set a value to this field. How can I do that?

noamyg
  • 2,747
  • 1
  • 23
  • 44
  • possible duplicate of [Dynamically access object property using variable](http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Paco Abato Dec 15 '14 at 09:28
  • I can't use bracket notations because I can't know which object the user is trying to set – noamyg Dec 15 '14 at 09:43

1 Answers1

0

If you want to assign a value to a new variable with a variable name, in the global scope, you can just do this:

function someFunction(expression){
    window[expression] = 1234;
}

There is really no good excuse to use evil()

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • You assume that the object is under "window". I want to provide a power user a way to write the whole object path as a string. – noamyg Dec 15 '14 at 09:30
  • Then you'll want to do something like this: http://stackoverflow.com/questions/8817394/javascript-get-deep-value-from-object-by-passing-path-to-it-as-string – Cerbrus Dec 15 '14 at 09:32
  • That should do it, I just thought that there would be a shorter way. Thanks – noamyg Dec 15 '14 at 09:52
  • @user3367818: sure, `eval` would be shorter, but it's _very_ dangerous. In case this answer or the comments helped you, please consider accepting it :-) – Cerbrus Dec 15 '14 at 09:53