0

I have an object that looks like this:

const mappings = {
  greeting: {
    'en': [
      'Hello',
      'Hi',
      'Hey'
    ],
    'it': [
      'Ciao',
      'Buongiorno',
      'Buonasera'
    ]
  }
}

Based on the language in the query, I would like to pick that language up. So I tried const language = req.query.language which can be it or en. But when I try to return Hello or Ciao mappings.greeting.language[0] it does not return anything, because it doesn't pick up the variable language.

How can I pass the variable in my query?

Tom Bom
  • 1,589
  • 4
  • 15
  • 38
  • try this `mappings.greeting[language][0]` instead of this `mappings.greeting.language[0]`. Because there is no field with this name in your `mappings` array. – Narendra Jadhav Aug 28 '18 at 04:40
  • Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – 31piy Aug 28 '18 at 04:44

2 Answers2

0

Since language is a variable, instead of dot notation (.) use bracket notation ([]) which allows property names as variables:

mappings.greeting[language][0]

const mappings = {
  greeting: {
    'en': [
      'Hello',
      'Hi',
      'Hey'
    ],
    'it': [
      'Ciao',
      'Buongiorno',
      'Buonasera'
    ]
  }
}
let language = 'en'
console.log(mappings.greeting[language][0])
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

I have done this code :

const language='en';
const mappings = {
  greeting: {
    'en': [
      'Hello',
      'Hi',
      'Hey'
    ],
    'it': [
      'Ciao',
      'Buongiorno',
      'Buonasera'
    ]
  }
};
console.log(mappings.greeting[language][0])
Aneesh Jose
  • 375
  • 6
  • 18