Lukas
Lukas

Reputation: 111

JavaScript: How to create object property name and value from variables

I'm working on choices gathering app and I got stuck at working with objects: User have list of cards, each card have list of choices, each choice have id and price. I want to gather user selection at each card and than count final price. I don't know exact names of cards, they will be generated. I know only the class of selected card or card list count.

data collection:

var datacollection = {
    shape: {
        itemId: 1,
        price: 10
    },
    countmoney: function () {
        var cash = 0;
        $.each(this, function (id, item) {
            if (typeof (item) != 'function') {
                cash += item.price;
            }
        });
        return cash + ' $';
    }
};

data gathered from .click(function() {

var cardClass = 'color';
var choiceId = 2;
var choicePrice = 50;

I can insert new data, but ONLY if I know name of the card

datacollection.color = {
    itemId: choiceId,
    price: choicePrice
};

But what if I don't know the possible name of card? Using bracket notation should be the way to go.. but it doesn't work.

cardClassTwo = 'material';

datacollection[cardClassTwo]['itemId'] = choiceId;
datacollection[cardClassTwo]['price'] = choicePrice;
// Uncaught TypeError: Cannot set property 'itemId' of undefined

console.log(datacollection.countmoney());

Code to play with: http://jsfiddle.net/F5pt6/

Upvotes: 0

Views: 182

Answers (1)

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

Initialize your datacollection['material'] as an object, like you did before.

Also, refer to values correctly (if they are in your previous object):

datacollection[cardClassTwo] = {
   itemId: datacollection.color.itemId,
   price: datacollection.color.price
};

Upvotes: 1

Related Questions