user3903685 user3903685 - 6 months ago 8
jQuery Question

Get object value by JavaScript variable

Okay, I have this code

localStorage.lang = "th"
var k;
switch(localStorage.lang){
case "th":
k = "NameThai";
break;
case "en":
k = "NameEnglish";
break;
}

$("#test").html(some.object.properties.k);


If
localStorage.lang
is
'th'
, I expect
k
to be
"NameThai"
, and
$("test").html
is set to
some.object.properties.NameThai


And if If
localStorage.lang
is
'en'
, I expect
k
to be
"NameEnglish"
, and
$("test").html
is set to
some.object.properties.NameEnglish


I know my code is wrong, since
k
in
$("#test").html(some.object.properties.k);
does not refer to variable
k
, but refers to object
k
instead.

Are there any way to achieve this?

Answer

yes use bracket notation, like this..

$("#test").html(some.object.properties[k]);
Comments