SETUP Description:
I am building a trivia game that has a spinner. This spinner is split up into 6 categories (the 6th category being ALL previous 5 categories combined). The first 5 categories will have it's own set of questions. Once the spinner stops on a category a form appears that will ask a series of questions in order according to it's category. Each question has 3 choices, 1 of them being the correct choice.
Below is a short question bank array to illustrate what I am thinking:
```
var questionBankArray =
[{
category: "Category1",
question: "What does the following expression return? <br> 3 / 'bob';",
choices: ["undefined", "ReferenceError", "NaN"],
correctAnswer: "NaN"
},{
category: "Category1"
question: "What is a method?",
choices: ["Used to describe an object.", "A function assigned to an object.", "Performs a function on one or more operands or variables."],
correctAnswer: "A function assigned to an object."
},{
category: "Category2"
question: "Which company first implemented the JavaScript language?",
choices: ["Netscape Communications Corp.", "Microsoft Corp.", " Sun Microsystems Corp."],
correctAnswer: "Netscape Communications Corp."
},{
category: "Category2"
question: "When was the first release of a browser supporting JavaScript?",
choices: ["1996", "1995", " 1994"],
correctAnswer: "1995"
},
];
```
I would like to go through the questionBanArray of objects, and by category, shuffle within that category. I also want to be able to shuffle the choices within each question of that category. How would I go about this? Would it be harder easier to rewrite it to look like this:
questionBankArray =
[{
CategoryBank1:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}],
CategoryBank2:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
}];
I think the ideal structure would be something like this:
questionBankArray =
[{
category:"first category",
questions:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
},
{
category: "second category",
questions:
[{
question1: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
},{
question2: "What is blank?",
choices: ["choice1","choice2","answer"],
answer: "answer"
}]
}];
Create a shuffle function:
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
Start looping over your outer array and go deeper and deeper, applying the shuffle function from the most inner level to the outer array
for (var category in questionBankArray) {
for (var question in category.questions) {
shuffle(question.choices);
}
shuffle(category);
}
shuffle(questionBankArray);
Related
I have this data...
{"quiz":
[{"question":"What is your favorite color?",
"choices":[{"prefix":"A","content":"Red"},{"prefix":"B","content":"Blue"},{"prefix":"C","content":"Yellow"},{"prefix":"D","content":"Pink"}]},
{"question":"What is the equivalent measurement of 1 feet?",
"choices":[{"prefix":"A","content":"12cm"},{"prefix":"B","content":"12px"},{"prefix":"C","content":"12mm"},{"prefix":"D","content":"12inch"}]},
{"question":"What is the combination of Green?",
"choices":[{"prefix":"A","content":"Yellow and Red"},{"prefix":"B","content":"Blue and Orange"},{"prefix":"C","content":"Yellow and Blue"},{"prefix":"D","content":"Black and Skyblue"}]}],"success":1}
and i want to convert it in java script like this one...
const myQuestions = [
{
question: "Who is the strongest?",
answers: {
a: "Superman",
b: "The Terminator",
c: "Waluigi, obviously"
},
correctAnswer: "c"
},
{
question: "What is the best site ever created?",
answers: {
a: "SitePoint",
b: "Simple Steps Code",
c: "Trick question; they're both the best"
},
correctAnswer: "c"
},
{
question: "Where is Waldo really?",
answers: {
a: "Antarctica",
b: "Exploring the Pacific Ocean",
c: "Sitting in a tree",
d: "Minding his own business, so stop asking"
},
correctAnswer: "d"
}
];
how can I achieve this one, because im making a quiz app which will view in mobile device by the use of webviewer. any help is much appreciated..
Here's a start of how you could potentially convert the array. Be aware, there is no correctAnswer column in your input, so it's impossible to convert:
var input = {"quiz":
[{"question":"What is your favorite color?",
"choices":[{"prefix":"A","content":"Red"},{"prefix":"B","content":"Blue"},{"prefix":"C","content":"Yellow"},{"prefix":"D","content":"Pink"}]},
{"question":"What is the equivalent measurement of 1 feet?",
"choices":[{"prefix":"A","content":"12cm"},{"prefix":"B","content":"12px"},{"prefix":"C","content":"12mm"},{"prefix":"D","content":"12inch"}]},
{"question":"What is the combination of Green?",
"choices":[{"prefix":"A","content":"Yellow and Red"},{"prefix":"B","content":"Blue and Orange"},{"prefix":"C","content":"Yellow and Blue"},{"prefix":"D","content":"Black and Skyblue"}]}],"success":1}
console.log(input.quiz.map(({question, choices}) => ({
question,
answers: choices.reduce((obj, v) => Object.assign(obj, {[v.prefix]: v.content}), {}),
correctAnswer: "?",
})));
const myQuestions = [
{
level:"Level 1",
questionNo: 1,
sentence: "Her uncles are army officers.",
question: "Q . Which words are about people? ",
answers: {
"1": "a. uncles / officers",
"2": "b. her/are",
"3": "c. in/the"
},
correctAnswer: "1",
topic: "Noun",
description: "plural nouns"
},
{
level:"Level 1",
questionNo: 2,
sentence: "He dropped the glass and it broke into many pieces.",
question: "Q . Which word stands for 'the glass'?",
answers: {
"1": "a. he",
"2": "b. it",
"3": "c. into"
},
correctAnswer: "2",
topic: "Pronoun",
description: "pronoun 'it' and what it has already referred to"
},
....
]
This is my JSON. Here my Html5 codes below
<div class="answers"> ${answers.join("")} </div>
Now we got key and values also like this.
1: a. uncles / officers
But we want only values. Anybody can solve this bug?
You can use Object.values() for this:
${Object.values(answers).join("")}
const myQuestions = [{
level: "Level 1",
questionNo: 1,
sentence: "Her uncles are army officers.",
question: "Q . Which words are about people? ",
answers: {
"1": "a. uncles / officers",
"2": "b. her/are",
"3": "c. in/the"
},
correctAnswer: "1",
topic: "Noun",
description: "plural nouns"
}];
console.log(Object.values(myQuestions[0].answers).join(', '));
When you do:
answers.join("")
then the join method is applied to the entire answers object, and it will concatenate both its keys and values.
In order to feed only the values to join, do:
Object.values(answers).join("")
More specifically:
var answers = myQuestions[0].answers;
console.log(Object.values(answers).join(""));
(as shown in this codepen).
const myQuestions = [{
level: "Level 1",
questionNo: 1,
sentence: "Her uncles are army officers.",
question: "Q . Which words are about people? ",
answers: {
"1": "a. uncles / officers",
"2": "b. her/are",
"3": "c. in/the"
},
correctAnswer: "1",
topic: "Noun",
description: "plural nouns"
}]
const ans = Object.values(myQuestions[0].answers)
console.log(ans)
I am trying to learn/use Node and Javascript by re-coding a PHP/MYSQL application I made that is not very efficient - as I built it while I was trying to earn those technologies as well.
I am trying to re-use a some of the information that is created or stored in JSON format.
I have in one file a set of 52 questions that looks like such...
//questions.json
{
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
},
"Administration" : {
"Question 9": "Administration positively supports faculty in a professional manner.",
"Question 10": "Administration actively encourages a dialogue concerning school related issues.",
"Question 11": "Administration is actively engaged in developing/supporting/maintaining a clear school vision.",
"Question 12": "Administration makes sure that the financial stability and integrity of the school is well maintained.",
"Question 13": "Administration/Ownership uses school funds to support the well being of the school."
},...
I also have a Knex script that does a query on the data and returns an array like below....
[ { Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5,
Q9: 7.63,
Q10: 8.13,
Q11: 8.5,
Q12: 8.88,
Q13: 8.75,
Q14: 7.38,
Q15: 8.13,
Q16: 8.56,...
I would like to try to combine these two arrays to look like...
{
"School" : {
{"Question 1" : {
"Question" : "The facilities of the school adequately provide for a positive learning/working experience.",
"Average" : 8.44
},
{"Question 2" : {
"Question" : ""School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc."",
"Average" : 9.13
}
If need be I can remove the category divisions within the .json file if that make combining easier, but in the end applications I display the data in sections, so I will eventually filter it. I just thought maybe dividing it in the json file would make it easier.
I am able to concat the arrays, and I have looked at .map but I am not sure how I would apply it to this. It looks like I would need a nested loop?
Using a double forEach loop:
const questions = {
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
}
};
const scores = {
Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5
};
// Placeholder for your result
const result = {};
// Iterate through the question categories:
const categories = Object.keys(questions);
categories.forEach(cat => {
// Add category to result
result[cat] = {};
// Get the question keys for that category
const questionKeys = Object.keys(questions[cat]);
questionKeys.forEach(q => {
// Get the score key. i.e: Question 1 -> Q1
const scoreKey = q.replace('Question ', 'Q');
// Add question to result
result[cat][q] = {
Question: questions[cat][q],
Average: scores[scoreKey]
};
});
});
console.log(result);
What I do below is basically:
I take the question number out of "Question 1"
Combine it with "Q" to get "Q1"
And then the plain old key lookup in the object you have based on this new string.
All this, in loops below
var newObj = {};
// replace /*questions.json*/ with your actual object.
for (var category in /*questions.json*/){
var questionsObj = /*questions.json*/[category];
newObj[category] = {}
for (var question in questionsObj) {
newObj[category][question] = {};
newObj[category][question].question = questionsObj[question];
var qNumber = question.split("Question ")[1];
newObj[category][question].Average = dataArray[0]["Q"+qNumber];
}
}
So, I need to put the following code into a JSON file and load it into a separate JavaScript file:
var allQuestions = [{
question: "What is Elvis Presley's middle name?",
choices: ["David", "Aaron", "Eric", "Jack"],
correctAnswer: 1
}, {
question: "Who is the singer of the Counting Crows?",
choices: ["Adam Duritz", "John Adams", "Eric Johnson", "Jack Black"],
correctAnswer: 0
}, {
question: "Who is the Queen of Soul?",
choices: ["Mariah Carey", "Whitney Houston", "Aretha Franklin", "Beyonce"],
correctAnswer: 2
}, {
question: "Which famous group was once known as The Quarrymen?",
choices: ["The Beatles", "The Birds", "The Who", "Led Zeppelin"],
correctAnswer: 0
}];
In other words, the contents of allQuestions need to go in a JSON file and then loaded into the allQuestions variable in a separate JavaScript file. What would the JSON file look like and how would I load it into the allQuestions variable?
Try using JSON.stringify() , $.getJSON()
What would the JSON file look like
"[
{
"question": "What is Elvis Presley's middle name?",
"choices": [
"David",
"Aaron",
"Eric",
"Jack"
],
"correctAnswer": 1
},
{
"question": "Who is the singer of the Counting Crows?",
"choices": [
"Adam Duritz",
"John Adams",
"Eric Johnson",
"Jack Black"
],
"correctAnswer": 0
},
{
"question": "Who is the Queen of Soul?",
"choices": [
"Mariah Carey",
"Whitney Houston",
"Aretha Franklin",
"Beyonce"
],
"correctAnswer": 2
},
{
"question": "Which famous group was once known as The Quarrymen?",
"choices": [
"The Beatles",
"The Birds",
"The Who",
"Led Zeppelin"
],
"correctAnswer": 0
}
]"
how would I load it into the allQuestions variable?
$.getJSON("/path/to/json", function(data) {
var allQuestions = data;
})
jsfiddle https://jsfiddle.net/dydhgh65/1
You can use the ES6 fetch API, like so:
// return JSON data from any file path (asynchronous)
function getJSON(path) {
return fetch(path).then(response => response.json());
}
// load JSON data; then proceed
getJSON('/path/to/json').then(data => {
// assign allQuestions with data
allQuestions = data;
}
Here is how to do it using async and await.
async function getJSON(path, callback) {
return callback(await fetch(path).then(r => r.json()));
}
getJSON('/path/to/json', data => allQuestions = data);
Try this:
var myList;
$.getJSON('JsonData.json')
.done(function (data) {
myList = data;
});
I need to remove one of the 'answers' objects nested in the Doc below. I have the text of the answer I'm looking for. I don't have the index of the question OR the answer that I need to drill down into the arrays.
For example, I know that the text of the question I'm trying to drill down into is "This is a question." and the answer I want to delete is "Answer One".
How would you go about doing that?
Here's the sample MongoDB Doc:
(Quizzes have Questions; Questions have Answers)
{
name: "Sample Quiz",
categories: [
{ name: "testcategory1", description: "this is a test category" }
,{ name: "categoryTWO", description: "the second category" }
],
questions: [
{ text: "This is a question."
,answers: [
{text: "Answer One", affected_categories: "testcategory1"}
,{text: "Answer Two", affected_categories: "testcategory1"}
,{text: "Answer Three", affected_categories: "categoryTWO"}
]
}
,{ text: "This is the second question."
,answers: [
{text: "Mepho One", affected_categories: "testcategory1"}
,{text: "Answer Toodlydoo", affected_categories: "testcategory1"}
,{text: "Lehmen Sumtin", affected_categories: "categoryTWO"}
]
}
],
}
When I was deleting an item that was nested a single level down (in this case, a question), I was able to do it with a query like:
Quizzes.update(
{ _id: quizID, 'questions.text': questionText },
{ $pull: { questions: {text: questionText }}}
);
(as described here: http://docs.mongodb.org/manual/core/update/#Updating-ModifierOperations , in the section titled "Update an Element without Specifying Its Position")
I tried expanding that to something like:
Quizzes.update(
{ _id: quizID, 'answers.text': answerText },
{ $pull: { questions: {text: questionText {answers: {text: answerText }}}}}
);
but didn't have any luck.
Any ideas would be greatly appreciated.
Use the positional operator in combination with $pull condition:
> db.quizzes.update(
{_id:<quizID>, "questions.text":"This is the second question."},
{$pull:{ "questions.$.answers":{"text":"Answer Toodlydoo"}}}
);
The above works to remove the second answer from the second question.