javascript - Syntax error when accessing property by variable? -
i have json variable stored in $("#budget").data('allocations')
i can access it's data this:
id = "5"; alert( $("#budget").data('allocations')[id].amount ); but need access this:
var id = "5"; var field = "amount"; alert( $("#budget").data('allocations')[id].[field] ); using variable in property name causes fail.
missing name after . operator (referring [field])
basically, .xxx can replaced ["xxx"] , there no limit in combining. use same logic used id:
$("#budget").data('allocations')[id][field] whenever key in variable, replace .key [variable]. so, obj.key1.key2 becomes obj[variable1][variable2] same logic.
Comments
Post a Comment