Variable name getting added instead of its value, javascript

前端 未结 3 1328
余生分开走
余生分开走 2020-12-12 05:27

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         


        
相关标签:
3条回答
  • 2020-12-12 06:06

    You will need to replace

    {category:rating}
    

    with

    var obj = {};
    obj[category] = rating;
    
    0 讨论(0)
  • 2020-12-12 06:15

    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;
    
    0 讨论(0)
  • 2020-12-12 06:25

    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.

    0 讨论(0)
提交回复
热议问题