Basic Javascript for Quiz [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am creating a very basic quiz app using Javascript and was wondering what would be the best way to nest arrays/objects. I have done this before with just simple one level nesting but feel that this project might need more.
The quiz needs to have 5 questions with multiple answers. Each answer will have a points value associated with it. When the quiz has been completed it will take the average of the points to then give you a type ie. 'You nostly ticked A's', 'You mostly ticked B's' etc. Similar to the quizzes you get in magazines.
I believe it should be something like this:
var quizList = {
"question": "What's your favourite Color",
"answers": {
["a","Blue","2"],
["b","Green","4"],
["c","Red","6"],
["d","Orange","8"],
},
"question": "What's your favourite Animal",
"answers": {
["a","Dog","2"],
["b","Cat","4"],
["c","Caterpiller","6"],
["d","Donkey","8"],
}
};
Is this correct and if so how would I call the various array elements?

Is this correct
Not really. That's not an array, it's an object literal which contains nested object literals and arrays. It also contains a pretty large problem; you're overwriting the previous question/answers keys with each new question/answer. You can't have two properties with the same name in an object. You've effectively done this:
{ a: 'b', a: 'c' }
Which is going to throw out the 'b' and set a to 'c'.
You probably need to rethink the structure so the top-level element is an array:
var quizList = [
{
"question": "What's your favourite Color",
"answers": [
["a","Blue","2"],
["b","Green","4"],
["c","Red","6"],
["d","Orange","8"],
]
}, {
"question": "What's your favourite Animal",
"answers": [
["a","Dog","2"],
["b","Cat","4"],
["c","Caterpiller","6"],
["d","Donkey","8"],
]
}
];
... and if so how would I call the various array elements?
And you can't "call" these array elements. They're not executable code, they're dumb data. You need to write a program which uses this object as its input, and generates a <form> containing a series of <input> or <select> elements.

I believe that the the best way would be something like this:
var quizList = [{
question: "What's your favourite Color",
alternatives: [
{ letter: "a", text: "Blue", value: "2" },
{ letter: "b", text: "Green", value: "4" },
{ letter: "c", text: "Red", value: "6" },
{ letter: "d", text: "Orange", value: "8" },
]
}, {
/* other question */
}];
As pointed, your quizList is not an array.

This part is invalid:
"answers": {
["a","Dog","2"],
["b","Cat","4"],
["c","Caterpiller","6"],
["d","Donkey","8"],
}
answers is an object (because of the {}), so it needs to have a key and a value. Perhaps you meant this:
"answers": [
["a","Dog","2"],
["b","Cat","4"],
["c","Caterpiller","6"],
["d","Donkey","8"],
]
Which is now an array which contains 4 nested arrays.
But I'd rather change it to this:
"answers": [{
letter: "a",
text: "Dog",
value: "2"
},
//...etc
]
By making your options objects rather than arrays, you have a more robust way to get at the properties for each answer. So instead of:
var letter = someAnswer[0]; // is this the right index??
You can do this:
var letter = someAnswer.letter; // now I know it's the right one
Your code will be much easier to maintain this way and you won't have to remember which index is which part of your answer.
Overall, I'd go with something like this:
var quizList = [{
question: "What's your favourite Color",
answers: [{
letter: "a",
text: "Dog",
value: "2"
},
// etc
]
},
// etc
];
Now at the top level quizList is an array of objects and each object has a property question and another property answers which is an array of objects with properties letter, text and value.

var quizList={
"questions":[
{
"question": "What's your favourite Color",
"answers": {
"a":{
"text":"Blue",
"point":"2"
},
"b":{
"text":"Green",
"point":"4"
},
"c":{
"text":"Red",
"point":"6"
}
"d":{
"text":"Orange",
"point":"8"
}
}
},
{
"question": "What's your favourite Animal",
"answers": {
"a":{
"text":"Dog",
"point":"2"
},
"b":{
"text":"Cat",
"point":"4"
},
"c":{
"text":"Monkey",
"point":"6"
}
"d":{
"text":"Donkey",
"point":"8"
}
}
}
]
};
Try this with a json format.

Related

How to analyze/count an array of objects in Javascript

Stack Overflow! This is my very first.
So, say for example I have the following array:
[
{
"question1": "Apple",
"question2": 5,
"question3": "Item 1"
},
{
"question1": "Apple",
"question2": 4,
"question3": "Item 2"
},
{
"question1": "Orange",
"question2": 4,
"question3": "Item 2"
}
]
Each object represents a respondent's answers to each question from a survey, which means the array above has a total of 3 responses.
What I want is to count the answers of each question, like how many in a multiple choice question chose X answer and so on.
The following output should look like this for a single question:
[
{
"answer": "Apple",
"count": 2,
},
{
"answer": "Orange",
"count": 1,
}
]
Which means according to the example above I'll need total of 3 arrays (because total 3 questions) of counted answers.
Is there any way to achieve this? My goal here is to use ChartJS in React to display charts of the responses of each question.
Final output for a single chart (of a single question, say question1):
[
{
"answer": "Apple",
"count": 2,
},
{
"answer": "Orange",
"count": 1,
}
]
This outputs an array of arrays of objects, instead of multiple array variables of objects. Since JavaScript objects preserve insertion order, you don't need to worry about the questions being out of order, assuming they're already in the proper order.
const data = [{question1:"Apple",question2:5,question3:"Item 1"},{question1:"Apple",question2:4,question3:"Item 2"},{question1:"Orange",question2:4,question3:"Item 2"}];
const newData = Object.values(data.reduce((acc, qna) => {
for (const [question, answer] of Object.entries(qna)) {
acc[question] = acc[question] ?? {};
acc[question][answer] = (acc[question][answer] ?? 0) + 1;
}
return acc;
}, {}))
.map((answerCount) => Object.entries(answerCount)
.map(([answer, count]) => ({ answer, count }))
);
console.log(newData);

How to add a new object to another within an array [duplicate]

This question already has answers here:
How to append something to an array?
(30 answers)
Closed 2 years ago.
I have an array which looks like this:
array = [
{code1:
{
number: 2,
name: "e"
}
},
{code2:
{
number:2,
name: "u"
}
}
]
and I want to add the following as a new object to say "code1" without changing the data it now has.
{
number: 3,
name: "j"
}
how can I do it? Thank you!
1st approach
If I understood what you want to do correctly this could work:
array = [
{code1:
{
number: 2,
name: "e"
}
},
{code2:
{
number:2,
name: "u"
}
},
{code1:
{
number: 3,
name: "j"
}
}
];
2nd approach
However this would make the structure more difficult to traverse. As an alternative you could make the whole thing into a dictionary of arrays, like this:˛
let object = {//doesn't matter what we call it
code1:[
{
number:2,
name: "e"
},
{
number:3,
name: "j"
}
],
code2:[
{
number:2,
name: "u"
}
]
};
You'd go about accessing the new object like this: console.log(object.code1[0].number);
You can try this approach out in the snippet bellow.
let object = {//doesn't matter what we call it
code1:[
{
number:2,
name: "e"
},
{
number:3,
name: "j"
}
],
code2:[
{
number:2,
name: "u"
}
]
};
console.log(object.code1[0].number);
Closing statement
But as I've already said, I'm not sure if I understood your question correctly, I'd suggest editting the question to make it clearer in the future.
Thanks for reading
Internet person out.

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)?
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)
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.
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}`);

Stringify in objects JSON inside a object JSON

This is my object JSON:
var myJSon = {
"Student": "name",
"Answers":{
"Answer1": {
"question": "question",
"answer": "black",
"time": "00:02:30",
"number_tentatives": "1"
},
"Answer2": {
"question": "question",
"answer": "black",
"time": "00:02:30",
"number_tentatives": "2"
}
}
};
I need to fill in the object "Answer1" or "Answer2". I tried
myJSon.Respostas = JSON.stringify("One","hello","00:03:22","1");
But this results in {Student":"\"name\"","Answers":"\"oi\"}
What I would like is {"Student": "\"name\"", "Answers": {"Answer1": {"question": "One", "answer": "hello" ,"time":"00:03:22" ,"number_tentatives": "1"}, "
If you have an object containing multiple answers, it should be an array or map of answers.
Let's think of your object's initial state as this:
var myJson = {student: 'Student Name', answers: []};
So then you could start filling the answers array like:
myJson.answers.push({question: 'q', answer: 'a', time: 1, number_tentatives: 1});
If you'd now access myJson.answers it would be an array with one answer in it.
If you still think the way to go would be objects (so a 'key' is assigned to each answer), you would do this, instead of push:
myJson.answers['answer1'] = {question: 'q', answer: 'a', time: 1, number_tentatives: 1};
If you want to add additional data, then you could try this:
myJSon.Answers.Answer3 ={"question":"One","answer":"hello","time":"00:03:22","number_tentatives":"1"};
then test it like
console.log(JSON.stringify(myJSon));

concatenation array of objects with javascript

I am taking questions from user and save them in DOM using Lawnchair.first step of declaration
var dbQuestions = new Lawnchair({name:'questions'}, function(obj) { consol('questions initialized'); });
User can input QuestionText,Choice,NextQuestionID and click save.Then each question is converted to below format
var survey= {
"name": "Internet Based survey",
"sortOrder":10,
"questions" : [
{ "QuestionID": "1", "SurveyID":1, "QuestionText":"Excuse me Sir/Madame, do you have 60 seconds to answer a few questions today?", "SortOrder":"10", "Choices": [{ "ChoiceID":"1", "Choice":"Yes", "NextQuestionID":"3", "InitiateSurvey":"true" },
{ "ChoiceID":"2", "Choice":"No", "NextQuestionID":"1" },
{ "ChoiceID":"3", "Choice":"What is it About?", "NextQuestionID":"2" }]
}]};
and saves
dbQuestions.save({key:'Q',value:survey},function(obj) {
consol('Question Saved successfully');
});
After saving first question user will enter next question. The above method works fine but i need to save in a different way. suppose user saves 3 questions and i want to store in below format so that i can access questions easily.
var survey = {
"name": "Internet Based survey",
"sortOrder":10,
"questions" : [
{ "QuestionID": "1", "SurveyID":1, "QuestionText":"Excuse me Sir/Madame, do you have 60 seconds to answer a few questions today?", "SortOrder":"10", "Choices": [{ "ChoiceID":"1", "Choice":"Yes", "NextQuestionID":"3", "InitiateSurvey":"true" },
{ "ChoiceID":"2", "Choice":"No", "NextQuestionID":"1" },
{ "ChoiceID":"3", "Choice":"What is it About?", "NextQuestionID":"2" }]
},
{ "QuestionID": "2", "SurveyID":1, "QuestionText":"It is about a way to earn a little extra money with a side business", "SortOrder":"15", "Choices":[{ "ChoiceID":"1", "Choice":"Yes", "NextQuestionID":"3", "InitiateSurvey":"true" },
{ "ChoiceID":"2", "Choice":"No", "NextQuestionID":"1" }]
},
{ "QuestionID": "3", "SurveyID":1, "QuestionText":"Are you on the internet?", "SortOrder":"10",
"Choices":[{ "ChoiceID":"4", "Choice":"Yes", "NextQuestionID":"4" },
{ "ChoiceID":"5", "Choice":"No", "NextQuestionID":"1" }]
}]};
So my question is how can i save questions where each question will save under question attribute.
Thanks in advance.
You can try this
var index = 0; // number of question
$.each(previousData.question,function(){
finalArray[index] = previousData.question[index]; //contain array
index++; //here index is number of question
});
finalArray[index] = data.question;
data = {'question': finalArray }; // convert array to object

Categories