UberCheetah
UberCheetah

Reputation: 11

How do we access the property of the object without calling object.property?

I'm pretty new to programming in general so this may be a very basic question.

Also English isn't my native language, my appologies if I don't express myself very well.

const questions = [{
      question: "what is 2 + 2 ?",
      answer: [{
        text: "4",
        correct: true
      }];
    ]

function showQuestion(question) {
  questionElement.innerText = question.question
}

I'm having trouble understanding, how do we access the question property of the object questions ("what is 2 + 2 ?") without calling its object.property(questions.question) but instead use parameter.property(question.question)?

Upvotes: 0

Views: 155

Answers (3)

user2721550
user2721550

Reputation:

const questions = [{
      question: "what is 2 + 2 ?",
      answer: [{
        text: "4",
        correct: true
      }]
      },
      {
      question: "what is 8 + 2 ?",
      answer: [{
        text: "10",
        correct: true
      }]
      },
       {
      question: "what is 8 - 4 ?",
      answer: [{
        text: "4",
        correct: true
      }]
      }
    ]


function showQuestion(id) {
 // questionElement.innerText = question.question
 console.log('question:'+ questions[id].question)
}

var id = Math.floor(Math.random() * questions.length)

showQuestion(id)

Upvotes: 1

Tom O.
Tom O.

Reputation: 5941

Another approach you you could use is a mixture of object destructuring and array destructuring to access object and array properties without explicitly specifying an index or using obj.prop. For example:

const questions = [{
  question: "what is 2 + 2 ?",
  answer: [{
    text: "4",
    correct: true
  }]
}];

const [{
  question,
  answer
}] = questions;

const [{
  text,
  correct
}] = answer;

console.log(`${question}: ${text}`);

Upvotes: 0

Barmar
Barmar

Reputation: 780889

questions is an array, presumably containing multiple objects like the one you showed. You call the function like this:

var i = Math.floor(Math.random() * questions.length); // Get random array index
showQuestion(questions[i]);

When you do this, the selected array element becomes the value of question in the function. You can then access its properties with question.propertyname.

If you still don't understand, you need to review your learning material, the section that explains function calling.

Upvotes: 0

Related Questions