Josh
Josh

Reputation: 63

Syntax error when accessing property by variable?

I have a json variable stored in $("#budget").data('allocations')

I can access it's data like this:

id = "5";
alert( $("#budget").data('allocations')[id].amount );

But I need to access it like this:

var id = "5";
var field = "amount";

alert( $("#budget").data('allocations')[id].[field] );

Using the variable in the property name causes it to fail.

missing name after . operator (referring to [field])

Upvotes: 0

Views: 131

Answers (1)

pimvdb
pimvdb

Reputation: 154908

Basically, .xxx can be replaced with ["xxx"] and there is no limit in combining. Just use the same logic you used for id:

$("#budget").data('allocations')[id][field]

Whenever the key is in a variable, replace .key with [variable]. So, obj.key1.key2 becomes obj[variable1][variable2] with the same logic.

Upvotes: 5

Related Questions