I would like to create a json object to send as a post array, but I need to create the key on the fly
var id = $('#myInput').val();
var post = {
'product[123]': 'myValue', // this works fine - but isn't dynamic
'product['+id+']': 'myValue' // this does not work
}
Sending it in as a string works fine, but I get an issue when I want to make it more dynamic. Am I missing something really simple here, or am I trying to do something Javascript isn’t supposed to do?
(Note that this has nothing to do with JSON. You’re not using JSON there, you’re using an object initializer. JSON is a textual (not code) format, which is a subset of JavaScript’s object initializer syntax.)
Do it outside the object initializer, using
[]notation:That will take the value (at runtime) of
product[id]and use that as the key for the property. If you wanted the key to literally beproduct[123]whenidis123, you’d use this instead:A more generic discussion:
JavaScript allows you to specify property keys in two ways: Using dotted notation and a literal (
obj.foo), or using bracketed notation and a string (obj["foo"]). In the latter case, the string doesn’t have to be a string literal, it can be the result of any expression.