Simon Dragsbæk
Simon Dragsbæk

Reputation: 2399

How can I use a string to access an object property?

I am trying to build this function that sets up my object for me

var schema = function(tableName, data) {
    return dataSet = {
        tableName: {
            1: data
        }
    };
};
var dataSet = schema("messages", data);

But when I execute this it returns tableName as a string, not using the variable that I pass through the function?

Is it possible to use the variable that I pass into my function as a name so that I get it returned like this:

{
    "message": {
        "1": {
            "username": "Simon",
            "message": "First message"
        }
    }
}

Instead of this:

{
    "tableName": {
        "1": {
            "username": "Simon",
            "message": "First message"
        }
    }
}

Upvotes: 1

Views: 47

Answers (1)

i_like_robots
i_like_robots

Reputation: 2787

Dot notation is not evaluated, but the square bracket syntax is:

var schema = function(tableName, data) {
    var dataSet = {};
    dataSet[tableName] = {
        1: data
    };
    return dataSet;
};

Upvotes: 5

Related Questions