Reputation: 21320
I am building some UI page using jQuery. In some function, i am creating a JavaScript object as
var key = "04:52:00";
var val = 13.21;
var data = {
key : val
};
When I try to loop through the data
object like,
for(var category in data) {
alert(category);
var points = data[category];
alert(points);
}
In the above, I am getting the value of val
variable correctly as 13.21
, but I am not getting key
variable value, instead in the alert(category);
, I am getting key
not 04:52:00
.
I am not much familiar with jQuery/JavaScript.
Upvotes: 0
Views: 47
Reputation: 72857
When initializing an object using a literal, like you're doing, you can't use variables for keys.
You'll have to use the bracket notation instead:
var data = {};
data[key] = val;
Upvotes: 1
Reputation: 318212
You have to use bracket notation to use variables as keys, when using dot notation or when creating an object, the key doesn't have to be quoted, and the literal string will be used as a key instead of the variable.
var key = "04:52:00";
var val = 13.21;
var data = {};
data[key] = val;
Upvotes: 3