0

I have an object:

"locales": {
    "en":["au", "uk"],
    "de":["ch", "de"]
 }

I check if a language is in this object then create the object with just the found language.

var language = 'en';

if(language in locales){

    locales = { language : locales[language]};
    ...

But logging locales gives:

{ language: [ 'au', 'uk' ] }

Where I would expect to see:

{ en: [ 'au', 'uk' ] }

The new object is using a string rather than var for the object key - how can I fix this?

0

3 Answers 3

1

You have to use Destructuring assignment here,

var language = 'en';
if(language in locales){
    locales = { [language] : locales[language]};

You can't use a variable directly as a key to an object.

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1
var locals = {}
locals[language] = locales[language];

Comments

1

locales = { language : locales[language]};

You have 2 problems:

  1. You set the key locales
  2. you use the locales twice

Do it like this:

var locales = {
    "en": ["au", "uk"],
    "de": ["ch", "de"]
        },
language = 'en';

if (locales[language]){
    locales = locales[language];
}

console.log(locales)

Output: enter image description here

2 Comments

i need the object to be called locales.
Updated the answer for you

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.