Graham Slick
Graham Slick

Reputation: 6870

String interpolation in AJAX call data parameter

I have a locale variable that can be en, fr, or es. I have to send an AJAX request, with the locale as the key of the data parameter.

let locale = "en";
let name = "example";
$.ajax({
  url: "/path",
  method: "PUT",
  data: {characteristic: {`${locale}`: name}},
  success: function(){},
  error: function(){}
})

I tried to use ES6's string interpolation, but it raises a syntax error. How can I do this ?

I'd like to get, depending on the locale:

{en: "example"}
{fr: "example"}
{es: "example"}

Upvotes: 3

Views: 870

Answers (3)

Ikbel
Ikbel

Reputation: 7851

This works:

[`${locale}`]: name

Upvotes: 1

Aron
Aron

Reputation: 9258

For this you can use computed property names:

{ [locale]: name } 

// if local is "en" the above will equal { "en": name }

In general, to use a computed property name you put the value to be computed in square brackets, like so:

{ [1 + 2]: 'three' } // is equal to { '3': 'three' }

Upvotes: 3

31piy
31piy

Reputation: 23869

Referencing from here, you need an array-like brackets to define dynamic property names:

{
  characteristic: {
    [locale]: name
  }
}

Upvotes: 0

Related Questions