String interpolation in data parameter of AJAX call
I have a variable locale
that can be en
, fr
or es
. I have to send an AJAX request, with the language course as the parameter key data
.
let locale = "en";
let name = "example";
$.ajax({
url: "/path",
method: "PUT",
data: {characteristic: {`${locale}`: name}},
success: function(){},
error: function(){}
})
I tried using ES6 string interpolation but it throws a syntax error. How can i do this?
I would like to get, depending on the language:
{en: "example"}
{fr: "example"}
{es: "example"}
+3
source to share
3 answers
You can use computed property names for this :
{ [locale]: name }
// if local is "en" the above will equal { "en": name }
In general, to use the computed property name, you put the value in square brackets, for example:
{ [1 + 2]: 'three' } // is equal to { '3': 'three' }
+3
source to share