jimmy118
jimmy118

Reputation: 323

unable to access object property through bracket variable notation

I am attempting to access one of the object propertie through a bracket notation, but I can not figure out why it is not working. As always, Your help is greatly appreciated!

js:

    var dude = [
      {
        question1: "What is dude's favourite food?",
        choices1: ["Pizza", "Pasta", "Chips", "Ice cream"],
        answer1: 1

      },
      {
        question2: "What was dude's first ever job?",
        choices2: ["Staples", "Vodafone", "Costa", "Post office"],
        answer2: 0
      },

    ]

var counter = 1;

var currentQues = "question"+counter;

console.log(dude[currentQues]);

The console returns "undefined". Is this because it can not access a property through a variable(currentQues), which essentially holds another variable(counter)?

As always, your help is greatly appreciated. I am just a beginner looking to advance.

Upvotes: 0

Views: 166

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

dude refers to an array of objects. You're trying to access question1 on dude, but you need to access it on dude[0]:

console.log(dude[0][currentQues]);
// -------------^^^

Live Example:

var dude = [
      {
        question1: "What is dude's favourite food?",
        choices1: ["Pizza", "Pasta", "Chips", "Ice cream"],
        answer1: 1

      },
      {
        question2: "What was dude's first ever job?",
        choices2: ["Staples", "Vodafone", "Costa", "Post office"],
        answer2: 0
      },

    ]

var counter = 1;

var currentQues = "question"+counter;

console.log(dude[0][currentQues]);


I would strongly recommend reconsidering that data structure. The names of the properties of the objects should be the same for all the objects, with just their position in the array differentiating them:

var dude = [{
    question: "What is dude's favourite food?",
    choices: ["Pizza", "Pasta", "Chips", "Ice cream"],
    answer: 1
  },
  {
    question: "What was dude's first ever job?",
    choices: ["Staples", "Vodafone", "Costa", "Post office"],
    answer: 0
  },
]

dude.forEach(function(entry, index) {
  var num = index + 1;
  console.log("Question #" + num + ": " + entry.question);
});

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386604

You need to take the index of the array as well.

var dude = [{ question1: "What is dude's favourite food?", choices1: ["Pizza", "Pasta", "Chips", "Ice cream"], answer1: 1 }, { question2: "What was dude's first ever job?", choices2: ["Staples", "Vodafone", "Costa", "Post office"], answer2: 0 }],
    counter = 1;
    currentQues = "question" + counter;

console.log(dude[counter - 1][currentQues]);
//               ^^^^^^^^^^^

Upvotes: 1

Related Questions