Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  184] [ 5]  / answers: 1 / hits: 53872  / 13 Years ago, sun, january 22, 2012, 12:00:00

This is what I'm trying to build via JavaScript in dot or [ ] notation:



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


Now if 'item1' is the variable name itemName.



This works:

var shoppingCart = {};

shoppingCart[itemName] = itemName;

alert(shoppingCart.item1);



Which returns item1



But this doesn't work:

1 var shoppingCart = {};

2 shoppingCart[itemName]['description'] = 'This is Item #1';



JS just dies at line 2, why? and how do I assign the description value to 'description'?



I would do it like this:



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


...but it makes the key literally itemName instead of item1.


More From » json

 Answers
12

shoppingCart[itemName] doesn't exist.

You need to create it first:



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


Or, better yet:



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

[#87863] Friday, January 20, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susand

Total Points: 690
Total Questions: 101
Total Answers: 104

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;