jspring
jspring

Reputation: 21

Javascript object literal name rule

I would like to use dot notation in an object literal name but IE returns an error: "Expected ':'" at line 16 after the partial 'my' statement (3rd from the bottom). There has to be a way to do something like this. Why is this returning an error?

<script language="javascript">
var my = {};
my.dataGridColumns = [];
var tmpArr = [];    
var columnData = [];

columnData.push("a");

my.dataGridColumns.push({
    id: 1,
    name: test
});

tmpArr.push({
    my.dataGridColumns[0].name: columnData[0]
});
</script>

Upvotes: 1

Views: 189

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

In JavaScript, you can treat an object like an associative array using []. You can take advantage of this to access property names dynamically.

How about:

var obj = { };
obj[my.dataGridColumns[0].name] = columnData[0];

tmpArr.push(obj);

Upvotes: 3

Related Questions