0

I want to create an object that has some keys which come from a variable parameter. Let's say for example that prod_id below is a variable containing some value... I want to create an object which has an attribute with key of that 'prod_id' and value of 1. However this does not work? Is this possible to achieve? if so, how? thanks a heaps

var cart_obj;
  cart_obj = {
  prod_id : 1
};
localStorage.setItem("cart", JSON.stringify(cart_obj));
LogixMaster
  • 586
  • 2
  • 11
  • 36
  • 1
    possible duplicate of [How do I add a property to a Javascript Object using a variable as the name?](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – T.J. Crowder Apr 17 '14 at 17:29
  • ...and searching gives us [this previous question and its answers](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name). Amazing, what a search can do. – T.J. Crowder Apr 17 '14 at 17:29

2 Answers2

2

You can't do it with a simple object literal. You can do this however:

var cart_obj = {};
cart_obj[prod_id] = 1;

JavaScript object literal syntax makes no provisions for expressions on the left side of a property declaration stanza.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1
var cart_obj = {};
cart_obj.prod_id = 1;

or

var cart_obj = {};
cart_obj[prod_id] = 1;
bobthedeveloper
  • 3,733
  • 2
  • 15
  • 31