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:
var id = $('#myInput').val();
var post = {};
post[product[id]] = 'myValue';
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 be product[123]
when id
is 123
, you'd use this instead:
post['product[' + id + ']'] = 'myValue';
A more generic discussion:
var a = "foo";
var obj = {};
obj[a] = "bar";
console.log(obj.foo); // "bar"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With