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);
0

1 Answer 1

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"]

Sign up to request clarification or add additional context in comments.

5 Comments

Could you explain why bracket notation should be used over dot notation here?
Both conventions would work but one is preferred over the other; by explaining the preferred approach would increase the value of this answer.
why does the . notation not work in my loop and yet the bracket notation does?
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.
There's an underscore in the variable name, dot notation doesn't like that. See here for more details on dot vs bracket

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.