I have a problem while adding values to a JavaScript object: the value to add is a key,value
pair. Here is sample:
//JavaScript object
var cart
You will need to replace
{category:rating}
with
var obj = {};
obj[category] = rating;
There is no way to use a variable to define a property name inside object literal notation. It accepts identifiers or strings, but both identify property names, not variables.
You have to create the object then add the property:
if(!cart[user]) {
cart[user] = {};
}
cart[user][category] = rating;
When creating an object literal the key must be a string, so in your code it will be "category". If instead you do:
var rating="1"
var category="somecat";
var user="user1";
if( !cart[user] ) {
cart[user]={};
}
cart[user][category]=rating;
That will initialise a non existing user to an empty object and then add the category.