Is there a way to transform a string as a path? [duplicate]

2
var sql = {
    datatypes: {

        integer:
        {
            INT: {
                mysql: 'INT'
            },
            SMALLINT: {
                mysql: 'SMALLINT'
            }
        }
    }
}

// Funciona
alert(sql.datatypes.integer.SMALLINT.mysql);

// Não funciona
teste("SMALLINT");
function teste(type){
     alert(sql.datatypes.integer.type.mysql);
}            
    
asked by anonymous 08.12.2016 / 13:30

2 answers

2

As you are submitting a string, simply switch to selection mode for:

sql.datatypes.integer[type].mysql

var sql = {
    datatypes: {

        integer:
        {
            INT: {
                mysql: 'INT'
            },
            SMALLINT: {
                mysql: 'SMALLINT'
            }
        }
    }
}

// Funciona
alert(sql.datatypes.integer.SMALLINT.mysql);

// Funciona também
teste("SMALLINT");
function teste(type){
     alert(sql.datatypes.integer[type].mysql);
}
    
08.12.2016 / 13:32
1

To access an attribute with the key as a string you must use [] brackets:

sql.datatypes.integer[type].mysql
    
08.12.2016 / 13:33