0

I'm having issues with this function I'm writing.

function addToCart(item) {
  let price = Math.floor(Math.random() * 100 + 1);
  cart.push({ item: price });
  console.log(`${item} has been added to your cart.`);
  return cart;
};

When I look at what's stored in my cart array, it has "item: 32" for example, rather than the item name that's passed as a parameter.

1 Answers1

3

Change

cart.push({ item: price });

to

var temp = {};
temp[item] = price;
cart.push(temp);

This create a new property on the temp object after object is declared.


If you can use ES6 then just do

cart.push({ [item]: price })

This evaluates the variable item at the time of object creation. In ES5, you cannot use a variable as a property name inside an object literal.

bugwheels94
  • 30,681
  • 3
  • 39
  • 60