0

Given an array of objects (greetings) containing enumerated name-value pairs:

const greetings = []
greetings.EN = {
  HELLO:  'Hello',
  BYE:    'Goodbye',
  SCRAM:  'Get lost'
}
greetings.ES = {
  HELLO:  'Hola',
  BYE:    'Asta luega',
  SCRAM:  'Vete'
}
greetings.FR = {
  HELLO:  'Bonjour',
  BYE:    'Au revoir',
  SCRAM:  'Allez-vous en'
}

The only way I can access an item is i.e.

console.log(greetings.EN.BYE)

Which can be implemented in 3 switch statements, one per language type see codepen

Rather than 3 switch statements, I would prefer use access an item with a syntax like :

let language = 'EN'
console.log(greetings.language.BYE)

which would allow me to directly access the translations without having to use the switch statements However, this produces a compiler error. Is there a way to resolve these values at run time?

user2978241
  • 311
  • 1
  • 5
  • 9
  • 5
    If you want to use a string as a key name, use this syntax `greetings[language].BYE` – Titus Nov 21 '19 at 20:16
  • 2
    Also, don't use non numeric keys with arrays ... Use an object instead – Jonas Wilms Nov 21 '19 at 20:17
  • bracket notation and should be `const greetings = {}` not [] – epascarello Nov 21 '19 at 20:17
  • There is [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) for these sort of things... I recommend starting by reading a [general guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction) before diving into [references](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference) though if you're not familiar with basic language features like property accessor notation. – Patrick Roberts Nov 21 '19 at 20:21

0 Answers0