Is there a way to transform a string as a path?

Asked

Viewed 56 times

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);
}            
  • 1

    Duplicate of http://answall.com/a/101938/129 (how to access properties of a JSON/Object dynamically)

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

2 answers

2

As you are sending a string, just switch to the selection mode to:

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);
}

1

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

sql.datatypes.integer[type].mysql
  • @jbueno thanks, always confusing the two haha

Browser other questions tagged

You are not signed in. Login or sign up in order to post.