13

Basically I have a form with a <select> that chooses which set of data to use (values are "m", "f" and "c"). I then have a dictionary/object with the data in:

var gdas = {
    // Male
    "m": {
        "calories": 2500,
        "protein": 55,
        "carbohydrates": 300,
        "sugars": 120,
        "fat": 95,
        "saturates": 30,
        "fibre": 24,
        "salt": 6
    },

    // Female
    "f": {
        "calories": 2000,
        // etc.
};

Now I need to get gdas.m/gdas.f/gdas.c but I'm not sure what syntax to use - I've tried:

var mode = $("#mode").val();
var gda_set = gdas.mode;
var gda_set = gdas[mode];

What's the right syntax/method for this?

2

3 Answers 3

21

Since you're referencing the property via a variable, you need the bracket notation.

var gda_set = gdas[mode];

...which is the same notation you would use if you were passing a String.

var gda_set = gdas["f"];
Sign up to request clarification or add additional context in comments.

2 Comments

You're right, I'm a bit confused as to why it didn't work the first time, probably had my break point in the wrong place. Thanks!
@Ross - You're welcome. :o) A fairly common mistake is to place a . before the opening bracket, as in gdas.[mode]. Anyway, glad you got it working!
2

You don't have "mode" attribute in that variable. You must use if's to detect which sex you are processing and get gdas.m.fibre or gdas.f.salt.

1 Comment

That's not really his question, is it? He needs to find out how he can make the .m. and .f. dynamic depending on the selected value
0

You can use gdas[mode], it selects the element that is indexed by the value of mode.

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.