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)
Related
I'm using an ajax request to grab some XML data which I then need to push into a chart in fusioncharts.
The XML data is formatted as [time taken], [work done], [which team done for], [who did it] (see below).
I'm iterating over the XML and then building the array using the code below:
//Time Recorded
if (columnidchecker == 7781) {
timearray.push($j(this).find('displayData').text());
temp1 = $j(this).find('displayData').text();
}
//Type of Activity
if (columnidchecker == 7782) {
activityarray.push($j(this).find('displayData').text());
temp2 = $j(this).find('displayData').text();
}
//Team Done For
if (columnidchecker == 7783) {
subjectarray.push($j(this).find('displayData').text());
temp3 = $j(this).find('displayData').text();
}
//Name
if (columnidchecker == 7777) {
internalclientarray.push($j(this).find('displayData').text());
temp4 = $j(this).find('userDisplayName').text();
}
});
//PUSH INTO A NEW ARRAY WHICH CAN THEN BE SORTED AND DE-DUPED WITH TIME COMBINED AGAINST ACTIVITY / TEAM.
objectarray.push([temp1, temp2, temp3, temp4]);
This builds an array of entries from the XML which basically outputs to something which looks like this:
0: (4) ["1.50", "Ad-hoc queries or calls", "Team 1", "James"]
1: (4) ["2.50", "Ad-hoc queries or calls", "Team 1", "James"]
2: (4) ["1.00", "Advice", "Team 2", "James"]
3: (4) ["3.50", "Meeting (External 3rd Party)", "Team 1", "James"]
4: (4) ["1.20", "Administration", Team 2", "James"]
5: (4) ["5.50", "Advice", "Team 1", "John"]
I'm trying to build a chart in fusioncharts which needs the format as shown below (ignore foot stuffs - it's taken straight from the fusioncharts help pages!).
{
"chart": {
"theme": "fusion",
"caption": "Revenue split by product category",
"subCaption": "For current year",
"xAxisname": "Quarter",
"yAxisName": "Revenues (In USD)",
"showSum": "1",
"numberPrefix": "$"
},
"categories": [
{
"category": [
{
"label": "Q1"
},
{
"label": "Q2"
},
{
"label": "Q3"
},
{
"label": "Q4"
}
]
}
],
"dataset": [
{
"seriesname": "Food Products",
"data": [
{
"value": "11000"
},
{
"value": "15000"
},
{
"value": "13500"
},
{
"value": "15000"
}
]
},
{
"seriesname": "Non-Food Products",
"data": [
{
"value": "11400"
},
{
"value": "14800"
},
{
"value": "8300"
},
{
"value": "11800"
}
]
}
]
}
The problem i'm having is that I cannot work out how to take the array of data with times, activity, team, name and push them into categories.
I think the first step is to create a new array of names which can be pushed into the "Category" data field in fusioncharts.
I then need a way in which to take the times being recorded against each activity and for each team and make sure it's assigned to the right person within the stacked bar chart and combine the amount of time spent. (i.e. "James" spent a total of 4 hours doing "Ad Hoc Queries and Calls" for Team 1 but this is split across two time entries so I need a way in which to combine them into one.)
Any help on this would be massively appreciated.
I can de-dupe the names to create a new array by using the following code:
namesarray.push(temp4);
uniq = [...new Set(namesarray)];
but after that it starts getting pretty complicated.
Maybe this can help you along the way. It's probably not exactly in the form you want it, but it demonstrates how you could break the problem down into smaller parts.
Pseudo-code:
get the unique names.
get the unique "task" names (for lack of a
better word)
for each unique person name:
3.1. get the data rows for that person
3.2 for each of all unique tasks names:
find the person data rows matching the task name
sum the duration of those data rows
const testData = [
[
"1.50",
"Ad-hoc queries or calls",
"Team 1",
"James"
],
[
"2.50",
"Ad-hoc queries or calls",
"Team 1",
"James"
],
[
"1.00",
"Advice",
"Team 2",
"James"
],
[
"3.50",
"Meeting (External 3rd Party)",
"Team 1",
"James"
],
[
"1.20",
"Administration",
"Team 2",
"James"
],
[
"5.50",
"Advice",
"Team 1",
"John"
]
];
const columnIndexByName = {
TASK_DURATION: 0,
TASK_NAME: 1,
FOR_WHICH_TEAM: 2,
PERSON_DOING_TASK: 3
};
const sum = (acc, next) => acc + next;
const uniqueNames = [...new Set(testData.map(row => row[columnIndexByName.PERSON_DOING_TASK])) ];
const uniqueTaskNames = [...new Set(testData.map(row => row[columnIndexByName.TASK_NAME])) ];
let result = {};
uniqueNames.forEach(personName => {
const personDataRows = testData.filter(row => row[columnIndexByName.PERSON_DOING_TASK] === personName);
let taskDurationsByTaskName = {};
uniqueTaskNames.forEach(taskName => {
const taskRows = personDataRows.filter(row => row[columnIndexByName.TASK_NAME] === taskName);
const taskDurations = taskRows.map(row => Number.parseFloat( row[columnIndexByName.TASK_DURATION] ));
const taskTotalDuration = taskDurations.reduce(sum, 0);
taskDurationsByTaskName[taskName] = taskTotalDuration;
})
result[personName] = taskDurationsByTaskName;
})
const renderData = data => document.querySelector("#output").innerHTML = JSON.stringify(data, null, 2);
renderData(result);
<pre id="output"></pre>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have assigned a task to group data in angular js using underscore js.
My JSON :
data = [
{
"Building*": "Building A",
"Wing*": "Wing C",
"Floor*": "Floor 3",
"Room Name*": "Room 3",
"Room Type*": "AC",
"Location*": "Location 1",
"Device ID*": 27,
"Category*": "Soap Hygene",
"Dispenser Name*": "Dispenser 34",
"Type*": "Manual",
"Cartridge Type*": "Type 1",
"Date of installation": "2016-04-11T06:06:22 -06:-30",
"Contact Last Name": "Maynard",
"Email Address": "thomas.boscher#gmail.com",
"Mobile Number with country code": "+1 (949) 590-3465",
"Description": "Description of device",
"Model": 37
},
{
"Building*": "Building B",
"Wing*": "Wing B",
"Floor*": "Floor 3",
"Room Name*": "Room 1",
"Room Type*": "AC",
"Location*": "Location 3",
"Device ID*": 26,
"Category*": "Soap Hygene",
"Dispenser Name*": "Dispenser 33",
"Type*": "Manual",
"Cartridge Type*": "Type 2",
"Date of installation": "2015-07-24T12:42:24 -06:-30",
"Contact Last Name": "Holland",
"Email Address": "thomas.boscher#gmail.com",
"Mobile Number with country code": "+1 (947) 491-2353",
"Description": "Description of device",
"Model": 32
}
]
I need data in below format, where it has each building details containing the wing and floor data
updateData = [{
building: 'Building A' ,
buildingData:[ {
wing: "Wing A",
wingData: [{
floor:'Floor 2',
floorData:[{
room:'Room 3',
roomData:[]
}]
}]
}]
}];
I tried :
js fiddle
But it fails. Need help. Thanks in advance.
From my understanding you want to groupBy in the following nested order:
Building ->> Wing ->> Floor ->> Room
You can try calling groupBy recursively (or looping through, up to you) by passing an array of the order of nested attribute you want to groupBy. Try this snippet below:
const nestedOrder = ['Building*', 'Wing*', 'Floor*', 'Room Name*']
function groupFilter (rawData, attrList) {
if (attrList.length == 0) return rawData
var currentAttr = _(attrList).first()
return _(rawData)
.chain()
.groupBy(currentAttr)
.map((list, attrName) => Object({
[currentAttr]: attrName,
[`${currentAttr}Data`]: groupFilter(list, _(attrList).rest())
}))
.value()
}
console.log(groupFilter(data, nestedOrder))
The raw data will then be compacted to the deepest nested attribute, in this case 'Room Name*', you can then write your custom filter to output what you want RoomData to hold.
Not sure if its the right way to do it, but if runtime isnt a big issue for you then I think you can make it work fine.
Hopefully this helps/works out for you.
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;
});
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);
Please Help,
I have created an object in a googleScript file which I have then have passed via a withSuccessHandler to an HTML file where I am then trying to iterate through the values in an object nested within the main object. We'll call it object_A, and it is defined below.
object_A = {
id=[axObsNum, axObAspect, axObElevation, axObLocation, axObCoordinates, axObDate, axObTrigger, axObType, axObSize, axObSlopeAngle, axObNotes],
parsed=[{3=[,,,,,2014-08-06,,,,,],2=[,,,,,2014-08-06,,,,,],1=[,,,,,2014-08-06,,,,,]}],
ob=[{"1":"","2":"","3":""}, {"1":"","2":"","3":""}, {"1":"","2":"","3":"","4":"","5":""}, {"1":"","2":"","3":""}, {"1":"","2":"","3":""}, {"1":"2014-08-06","2":"2014-08-06","3":"2014-08-06"}, {"1":"","2":"","3":""}, {"1":"","2":"","3":""}, {"1":"","2":"","3":""}, {"1":"","2":"","3":""}, {"1":"","2":"","3":""}],
key=[1, 2, 3, 4, 5],
header=[Ax Obs Num, Ax Ob Aspect, Ax Ob Elevation, Ax Ob Location, Ax Ob Coordinates, Ax Ob Date, Ax Ob Trigger, Ax Ob Type, Ax Ob Size, Ax Ob Slope Angle, Ax Ob Notes]
}
Specifically I want the parsed values of object_A. In the googleScript file I can easily get these be declaring object_A.parsed[0][2]. I know parsed is an array, so [0] gives me the first, and only, value in that array and then with the [2] i get the values for that key-value.
My question is, why doesn't this work in the html file where I've declared a simple function to handle the return from the the withSuccessHandler function. That simple code is as follows, and the result will be undefined.
function withSuccess(obj){
console.log(obj.parsed[0][2])
}
Why? Please Help. Thank you.
Change all your ='s to :s. That should fix your problem.
Object members are defined like this: { foo: "bar", bar: "baz" }. Equal signs are used for single assignment statements.
This would be likely more correct as per your above object (added line breaks for clarity):
object_A = {
id: [
axObsNum,
axObAspect,
axObElevation,
axObLocation,
axObCoordinates,
axObDate,
axObTrigger,
axObType,
axObSize,
axObSlopeAngle,
axObNotes,
],
parsed: [{
3: [,,,,,2014-08-06,,,,,],
2: [,,,,,2014-08-06,,,,,],
1: [,,,,,2014-08-06,,,,,],
}],
ob: [
{"1": "", "2": "", "3": ""},
{"1": "", "2": "", "3": ""},
{"1": "", "2": "", "3": "", "4": "", "5": ""},
{"1": "", "2": "", "3": ""},
{"1": "", "2": "", "3": ""},
{"1": "2014-08-06", "2": "2014-08-06", "3": "2014-08-06"},
{"1": "", "2": "", "3": ""},
{"1": "", "2": "", "3": ""},
{"1": "", "2": "", "3": ""},
{"1": "", "2": "", "3": ""},
{"1": "", "2": "", "3": ""},
],
key: [1, 2, 3, 4, 5],
header: [
"Ax Obs Num",
"Ax Ob Aspect",
"Ax Ob Elevation",
"Ax Ob Location",
"Ax Ob Coordinates",
"Ax Ob Date",
"Ax Ob Trigger",
"Ax Ob Type",
"Ax Ob Size",
"Ax Ob Slope Angle",
"Ax Ob Notes",
],
}
Note that your header property may also be spewing SyntaxErrors, so I gave a suggested fix above (assuming they are strings as they appear they should be).