Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
Ross Avatar asked Sep 12 '10 14:09

Ross


People also ask

How can you read properties of an object in JavaScript?

We can use the jQuery library function to access the properties of Object. jquery. each() method is used to traverse and access the properties of the object.

Is property of object JavaScript?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.

How do I get all the values of an object?

values() Method: The Object. values() method is used to return an array of the object's own enumerable property values. The array can be looped using a for-loop to get all the values of the object.


2 Answers

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"];
like image 176
user113716 Avatar answered Sep 21 '22 12:09

user113716


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.

like image 37
Tomasz Kowalczyk Avatar answered Sep 17 '22 12:09

Tomasz Kowalczyk