简体   繁体   中英

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"
        }
    }
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM