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

1

2 Answers 2

2

Use bracket notation instead:

console.log(data[letter][0]) // apples
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.