Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object with multiple values

I am trying to build a set of questions and answers for a questionnaire. Each instance has an id, a css class, a question, and at least one answer. Is it possible to have multiple values when there is more than one answer?

var qa = [
{id: "0", css: "multiple", question: "Do you own a home?", answers: "Yes", "No"},
{id: "1", css: "input", question: "Who will live in your home?", answer: "<textarea rows='5' class='textarea'></textarea>"}
];
like image 728
Solona Mead Avatar asked Jan 09 '23 12:01

Solona Mead


1 Answers

You can do this by turning the answers in to an array:

var qa = [{
            id: "0",
            css: "multiple",
            question: "Do you own a home?",
            answers: ["Yes", "No"]
}];

And than access it like this:

qa[0].answers[0] // for "Yes"
qa[0].answers[1] // for "No"

or

qa[0]['answers'][0]// for "Yes"
qa[0]['answers'][1] // for "No"

Or instead of an array you also can use an object:

var qa = [{
           id: "0",
           css: "multiple",
           question: "Do you own a home?",
           answers: [yes: "Yes", no: "No"]
}];

And than access it like this:

qa[0].answers.yes // for "Yes"
qa[0].answers.no // for "No"

or

qa[0]['answers']['yes']// for "Yes"
qa[0]['answers']['no'] // for "No"
like image 153
Mariksel Azemaj Avatar answered Jan 18 '23 17:01

Mariksel Azemaj