1

Sorry for the newbie question but I must be overlooking something. How do I set obj.{this.name} = property so obj.sandwich = off. My object would look something like:

obj { sandwich: off, soup: off }

http://jsfiddle.net/naaua4b5/

List of checkboxes:

<input type = "checkbox" name = "sandwich" />
<input type = "checkbox" name = "soup" />

js code:

var obj = {} ; 

$('input[type=checkbox]:not(:checked)').map(function()
{
     var item_name =  this.name;
     var value = 'off';
     obj.item_name = value;
}).get();

console.log (obj);
Huangism
  • 16,278
  • 7
  • 48
  • 74
Undermine2k
  • 1,481
  • 4
  • 28
  • 52

1 Answers1

5

Use bracket notation:

var obj = {} ; 
      $('input[type=checkbox]:not(:checked)').map(function()
                {
                    var item_name =  this.name;
                    var value = 'off';
                    obj[item_name] = value;// <-brackets!
                }).get();
console.log (obj);

dot notation obj.key accesses an object using the literal "key" and, although the norm, can be limiting depending on what you want to do. Bracket notation obj['key'] gives you a little more freedom where you can use a variable as the key (as in your case) or even throw crazy characters in there like obj["I'm-Acrazy_Key"]

KJ Price
  • 5,774
  • 3
  • 21
  • 34
  • 1
    Could you explain why bracket notation should be used over dot notation here? – Sterling Archer Apr 06 '15 at 20:08
  • Both conventions would work but one is preferred over the other; by explaining the preferred approach would increase the value of this answer. – Anthony Forloney Apr 06 '15 at 20:09
  • why does the . notation not work in my loop and yet the bracket notation does? – Undermine2k Apr 06 '15 at 20:10
  • Thanks for the comments. I sometimes get excited and throw answers up. I've edited to explain myself better. @Undermine2k, the end result is that bracket notation allows you to use variables for your key. – KJ Price Apr 06 '15 at 20:12
  • There's an underscore in the variable name, dot notation doesn't like that. See [here](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) for more details on dot vs bracket – Sterling Archer Apr 06 '15 at 20:15