C-Bertram
C-Bertram

Reputation: 99

How do I retrieve a value from an array using a variable with Node.js

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

Upvotes: 0

Views: 754

Answers (2)

Vaghani Janak
Vaghani Janak

Reputation: 611

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

Upvotes: 0

Evya
Evya

Reputation: 2375

Use bracket notation instead:

console.log(data[letter][0]) // apples

Upvotes: 2

Related Questions