Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically select a javascript object attribute

Tags:

javascript

[How] can I achieve the following?

var object = new Object();
object.field1 = "test1";
object.fiedl2 = "test2";

function showSpecificField(fieldName){
    //get the field Name passed in to function from object
    //something like: return object.fieldName ???
}

alert(showSpecificField("field2"));// should alert the text "test2"

alert(showSpecificField("field1"));// should alert the text "test1"
like image 446
kralco626 Avatar asked May 20 '11 11:05

kralco626


1 Answers

Use square bracket notation

var baz = 'bar';
foo['bar'] === foo.bar === foo[baz]
like image 59
Quentin Avatar answered Oct 30 '22 14:10

Quentin