3

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"}
2
  • Why do you need ES6's string interpolation? Commented Jul 10, 2017 at 8:03
  • 1
    I also tried string concatenation, didn't seem to work either. I'm open to any solution though Commented Jul 10, 2017 at 8:04

3 Answers 3

3

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' }
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting, didn't know about computed properties. Thanks for the additional example.
1

This works:

[`${locale}`]: name

Comments

0

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

{
  characteristic: {
    [locale]: name
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.