Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

json - Get property of object in JavaScript

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...