2

I need to run this line of Javascript:

@model.save({ name: @some_element.val() })

But the key, which in this case is name, will change depending on the value of a variable. The variable is a string representation of the key. So in this case, the variable is "name". How can I use the variable to specify the correct key? If I use the variable name directly it is interpreted as the key itself.

ben
  • 29,229
  • 42
  • 124
  • 179

1 Answers1

5
var obj = {};
obj[varName] = @some_element.val();
@model.save(obj);
Phil
  • 157,677
  • 23
  • 242
  • 245
  • I was just about to write that :) – Spycho Sep 02 '11 at 11:51
  • I normally prepend some character to varName, so to not overwrite predefined methods of the object. So for example obj['@' + varName] = ... – xanatos Sep 02 '11 at 12:05
  • @xanatos and where, between lines one and two, do you envision these "predefined" methods sneaking in? – Phil Sep 02 '11 at 12:58
  • @phil http://erik.eae.net/archives/2005/06/06/22.13.54/ and if you think it's a stupid scenario, please look here https://github.com/douglascrockford/JSON-js this is the most used JSON library for js, look at the description of json.js: *This file does everything that json2.js does. It also adds a toJSONString method and a parseJSON method to Object.prototype. Use of this file is not recommended* Still the file is present :-) – xanatos Sep 02 '11 at 13:19
  • @xanatos I get the feeling the object is used as some sort of configuration "map" for the `save()` method and as such, any modification of the key names would result in unwanted behaviour. I really cannot grasp the warning you're trying to alert me to in this case. The object is created, assigned a key / value and consumed. There is no scope for unexpected modification – Phil Sep 02 '11 at 14:45
  • @Phil If at the start of the code (you know, BEFORE your 3 lines) (or in any of the flocks of .js normally included) someone writes `Object.prototype.toJSON = function() {}` then EVERY NEW OBJECT will have a property named `toJSON`. Now, clearly if you add '@' at the beginning of the key, every time you look in the object you have to remember you added an @ at the beginning of the key. So if you want to look for `puppy` you'll need to look for `@` + `puppy`. The advantage is that if the name of your puppy is `toJSON`, you won't exchange it for mr. `toJSON, I Serialized Things`. – xanatos Sep 02 '11 at 15:17
  • @xanatos Fair enough but I get the feeling that; a) The `save()` method is part of a third party library, and b) It's highly unlikely anybody is adding prototypes to `Object`. – Phil Sep 02 '11 at 15:20