0

I have this jQuery:

$.post(document.URL, {'blanks':word});  
$.post(document.URL, {'blanks':{ word :{'time':T}}});

And this is the result when I log it in terminal:

{ blanks: 'plotted' }
{ blanks: { word: { time: '1386984059685' } } }

Why does the variable word not change in the second jQuery statement? I assume it has something to do with single quotes being added to the key name, but I couldn't figure a work around.

I solved my problem with

$.post(document.URL, {'blanks':{'word':word, 'time':T}});

which resulted in

{ blanks: { word: 'plotted', time: '1386984409890' } }

But I was curious as to why the variable didn't change when it was the key, and if there was a way to do it?

Squirrl
  • 4,909
  • 9
  • 47
  • 85
  • 1
    Keys cant be variables see http://stackoverflow.com/questions/6071471/javascript-object-variable-key – megawac Dec 14 '13 at 01:40

1 Answers1

1

If you define your data in advance, you can do this:

var someVar = 'foo';
var data = {};

data[someVar] = 'My key is "foo"';

console.log(data.foo);
console.log(data[someVar]);
console.log(data['foo']);

All of these will log My key is "foo"

When you are creating an object like this {prop: 'value'} The property name can't be a variable - what you type is what you get. The quotes are optional, unless you use characters that would otherwise throw an error. The same goes for accessing properties with dot notation like: myObj.propName.anotherPropName.

Bracket notation is more flexible in that you can access otherwise invalid property names and also use variables to set and access properties.

var myObj = {
  '@##%$#%%^&%' : 'some value'
};
console.log(myObj['@##%$#%%^&%']); //logs "some value"
m59
  • 43,214
  • 14
  • 119
  • 136