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
Related
I am using json-server as my fake API data. I am implementing the search functionality to it. I created an endpoint like this -
getData : ( searchTerm : string ) => axios.get(`http://localhost:3000/books?=${searchTerm}`).then((response) => setData(response));
and I am utilizing into my input field to get the searched results.
Let's say My json object coming back from the Json-server is as follows -
[
{
"Id": 1,
"name" : "car"
},
{
"Id": 2,
"name" : "bike"
},
{
"Id": 3,
"name" : "ninja bike"
}]
now, the problem is , when I search for "car", it gives me the json result.
but, when I search for "brand new car", it should give me the "car's" object at least, as word "car" is a match. but it is giving me [], empty array.
So please suggest me how could i look for specific words into my json-server's data?
so that whenever , the end user even make a vague unstructured search, it should look for specific words like "car", in this case and return that car object.
You can make a simple filter to check if your string is in there
let json = [{
"Id": 1,
"name": "car"
},
{
"Id": 2,
"name": "bike"
},
{
"Id": 3,
"name": "ninja bike"
}
]
let searchString = "brand new car".split(" ") // ["brand", "new", "car"]
let filter = json.filter(json => searchString.includes(json.name))
if (filter.length) {
console.log(filter[0].name)
console.log(filter[0].Id)
}
else console.log("not found")
I have a question about manipulating data in an associative array.
What I want to do
I want to verify if an order exists in sellingItems.
Background(why?)
I want to check if there is an order to return the number of products in stock as a response.
Question
I want to check if a specific data (order) exists in an associative array and calculate the inventory count.
public calculateStockQuantity(itemInstances) {
const stockQuantity = //We want to count the number of items in stock. In this case, we want it to be 2 (calculated based on whether the data exists in sellingItem.order or not).)
return stockQuantity;
}
Associative array of targets
//There are three itemInstances for one product because the number of products sold is three.
itemInstances =
[
{
"id": "1",
"sellingItem": [
{
"id": 1,
"price": 3000,
"orderedItem": [
{
"id": 1
"ordered_at": "2021-04-01 10:00:00"
}
]
}
]
},
{
"id": "2",
"sellingItem": [
{
"id": 2,
"price": 3000,
"orderedItem": []
}
]
},
{
"id": "2",
"sellingItem": [
{
"id": 2,
"price": 3000,
"orderedItem": []
}
]
}
]
Sorry for asking like a newbie.
Please check if this is something you are looking for, assuming if orderedItem array is empty then that sellingItem will be counted as in stock
let count = itemInstances.filter(({sellingItem : [{ orderedItem }]}) => orderedItem.length === 0).length;
console.log(count); //return 2 based on question data
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}`);
I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']
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.