在Javascript中为JSON对象赋值

时间:2012-01-22 22:03:25

标签: javascript json object assign

这是我试图通过JavaScript以点或[]表示法构建的:

var shoppingCart = { 
        'item1' : {
            'description' : 'This is item #1',
            'price' : 10,
            'quantity' : 1,
            'shipping' : 0,
            'total' : 10
        }
    };

现在,如果'item1'是变量名itemName

这有效:
var shoppingCart = {};
shoppingCart[itemName] = itemName;
alert(shoppingCart.item1);

返回item1

但这不起作用:
1 var shoppingCart = {};
2 shoppingCart[itemName]['description'] = 'This is Item #1';

JS刚刚在第2行去世,为什么?以及如何将描述值分配给'description'?

我会这样做:

var shoppingCart = { 
        itemName : {
            'description' : description,
            'price' : price,
            'quantity' : quantity,
            'shipping' : shipping,
            'total' : total
        }
    };

...但它确实按键itemName代替item1

4 个答案:

答案 0 :(得分:11)

shoppingCart[itemName]不存在 您需要先创建它:

var shoppingCart = {};
shoppingCart[itemName] = { };
shoppingCart[itemName].description = 'This is Item #1';

或者,更好的是:

var shoppingCart = {};
shoppingCart[itemName] = { description: 'This is Item #1' };

答案 1 :(得分:2)

在javascript对象中不会自动创建成员访问;你必须先创建对象:

var shoppingCart = {};
shoppingCart["item1"] = {}; // This creates the object
shoppingCart["item1"]["description"] = "This is item #1"; // add a member

注意,您当然也可以使用

一次创建整个对象
shoppingCart[itemname] = { "description": description,
                           "price": price,
                           "quantity": quantity,
                           "shipping": shipping,
                           "total": total };

答案 2 :(得分:1)

它不起作用,因为在第二个示例中,您尝试使用尚未设置的键索引空白对象。以下内容将有效......

var shoppingCart = {};
shoppingCart[itemName] = {};
shoppingCart[itemName]['description'] = '...';

因为现在shoppingCart [itemName]实际上是一个对象。

答案 3 :(得分:0)

仅供参考,替代解决方案:

var itemName = {};
itemName.description = 'This is Item #1';
var shoppingCart = {};
shoppingCart.itemName = itemName;

或只是

var shoppingCart = {};
shoppingCart.itemName = { description: 'This is Item #1' };