0

I'm fairly new to Node.js and was unsure how to title the question so apologies if it is misleading. I suspect it will be fairly straight forward but have been unable to find the answer whilst searching.

I have an array of values as shown below.

  const data = {
    "A": ["apples", "avocado", "antler","arrow",],
    "B": ["banana", "beetroot", "ball", "baboon",],
    "C":["carrot"],
    }

I can access the value apples by doing data.A[0] but I would like to use a variable to replace the letter so it can be changed dynamically.

For example

var letter = "A"
console.log(data.letter[0])

Is there something I am missing syntactically to allow for me to do this or is it something to do with it being a string?

Thank You

C-Bertram
  • 79
  • 6
  • 1
    Possible duplicate of [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Hassan Imam Oct 06 '18 at 09:58

2 Answers2

2

Use bracket notation instead:

console.log(data[letter][0]) // apples
Evya
  • 2,325
  • 3
  • 11
  • 22
0

You can use the following example to retrieve a value from an array using a variable with Node.js:

console.log(data[letter][0])     // apples
console.log(data.A[0]);          // apples
console.log(data['A'][0]);       // apples
Vaghani Janak
  • 601
  • 5
  • 14