0

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/

4
  • shouldn't $.each(this, function (id, item) { be $.each(datacollection, function (id, item) { as this in that scope, would be the equivalent of window Commented Dec 2, 2013 at 20:20
  • @RoryPicko92 not the way it's called. datacollection.countmoney() is calling it as a member of the object. Commented Dec 2, 2013 at 20:21
  • datacollection[cardClass] = { Commented Dec 2, 2013 at 20:22
  • @Mathletics oh yeah, of course!! Commented Dec 2, 2013 at 20:23

1 Answer 1

1

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
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.