Passing array from node.js/express to jade template - javascript

Not sure what I'm doing wrong here..
questions.js
questions = [];
questions.AA = 'First'
questions.BB = 'Second'
questions.CC = 'Third'
res.render('questions', { title: questions[CC], questions: questions });
questions.jade
extends layout
block content
h1= title
p #{questions.CC}
each question in questions
p= question
Rendered
<body>
<h1>Third</h1>
<p>Third</p>
</body>
So
each question in questions
p= question
Doesn't seem to be working as I would expect. What am I missing?

You created an array and then stored values into alphabetic indices rather than integer indices. As such, each will not loop over them. You probably mean to define questions like this:
questions = []
questions[0] = 'First'
questions[1] = 'Second'
questions[2] = 'Third'
Or, more idiomatically:
questions = [
'First',
'Second',
'Third'
]
You’ll have to figure something out to replace how you were getting the title, but this should fix the loop.

Related

Deleting or get rid of complete array which doesnt have all desired items in an array

delete array which doesnt have "category" field
req:wanted to get rid of obj[0] & obj[2] as they doesn't hav category field...
for example:
js data:
var obj=[
{"email":"rteh#tm.com","event":"open"},
{"ip":"24.38.43.233","email":"rtehrani#tmcnet.com","category":["webinar"]},
{"email":"glin#gl.com","event":"open"},
{"ip":"24.98.43.230","email":"glin#gl.com","category":["webinar"]},
{"ip":"24.77.55.931","email":"klen#gmail.com","category":["webinar"]},
{"ip":"44.67.85.456","email":"bryan#gmail.com","category":["webinar"]}
];
expected o/p:
var obj=[
{"ip":"24.38.43.233","email":"rtehrani#tmcnet.com","category":["webinar"]},
{"ip":"24.98.43.230","email":"glin#gl.com","category":["webinar"]},
{"ip":"24.77.55.931","email":"klen#gmail.com","category":["webinar"]},
{"ip":"44.67.85.456","email":"bryan#gmail.com","category":["webinar"]}
];
question is edited...for simple understanding,
thanks in advance....
I'm not sure I completely understand the question, but I'm assuming that you want to get rid of all objects that don't have a category property. This snippet would do it.
var obj=[
{"email":"rteh#tm.com","event":"open"},
{"ip":"24.38.43.233","email":"rtehrani#tmcnet.com","category":["webinar"]},
{"email":"glin#gl.com","event":"open"},
{"ip":"24.38.43.230","email":"glin#gl.com","category":["webinar"]}
];
var result = obj.filter(participation => participation.hasOwnProperty('category'));
console.log(result);

How to iterate objects in an array into many elements?

The answer to this is probably really simple but I just can't see it.
I have an array of objects whose information I want to display in various places. I want to put each question into a section h1, of which I have five. However, the code I came up with just inserts the question of the last object in the array into every section h1, i.e., they all say "Question 5". I can't figure out why. How do I make this print each question into a different section h1?
var questions = [
{question: "Question1", choices: ["A","B","C"], answer: 0},
//etc. x 5
];
$('section h1').each(function() {
for (var i = 0; i < questions.length; i++) {
$(this).text(questions[i].question);
}
});
The .each() callback function gets passed an index as the first parameter. You can use that to determine which question to show, instead of having to loop over all of them.
So change your code to:
var questions = [
{question: "Question1", choices: ["A","B","C"], answer: 0},
//etc. x 5
];
$('section h1').each(function(index) {
$(this).text(questions[index].question);
});
EDIT: Adding additional example for how to populate the choices.
You would need to do this by looping over each section, then finding the h1 and lis within that section to populate.
Like so:
var questions = [
{question: "Question1", choices: ["A","B","C"], answer: 0},
//etc. x 5
];
$('section').each(function(index) {
var question = questions[index], $section = $(this);
$section.find('h1').text(question.question);
$section.find('li').text(function (index) {
return question.choices[index];
});
});

Display json object dynamically

I have a json object in collection which I need to show it on the page.
Here is what I did:
I first call the helpers template then in that I fetch the json object from the collection:
I am using coffeescirpt and jade-handlebars, here goes my code in coffeescript:
Template.test.helpers
test: ->
test = Question.find().fetch();
test
In the console when I do Question.find().fetch() the following thing occurs:
QuestionData: Object
question1: "How many kids do I have ?"
question2: "when will i die ?"
question3: "how many wife do i have ?"
question4: "test"
__proto__: Object
_id: "w9mGrv7LYNJpQyCgL"
userid: "ntBgqed5MWDQWY4xt"
specialNote: "Rohan ale"
Now in the jade when I call the template by:
template(name="hello")
.test {{QuestionData}}
I can see only the [object] [object]. To see the question1,question2 I have to do the following:
template(name="hello")
.test {{QuestionData.question1}}, {{QuestionData.question2}}
How can I dynamically show all the questions without doing {{QuestionData.question1}} ...
Thank You in advance !!!
You can dynamically compose field names in a loop.
b = { q1: 'a1', q2: 'a2', q3: 'a3' };
for (x=1;x<=3;x++) { console.log( b[ 'q' + x ] ) }
That being said, there's a lot here that seems a misunderstanding to me. I'd step back and say that you should look into storing one question per mongo document. This gives you the easiest data for meteor to play with. Or, storing multiple questions in an array:
test = {
questions : [
"How many kids do I have ?"
"when will i die ?"
"how many wife do i have ?"
"test" ] ,
userid: "ntBgqed5MWDQWY4xt",
specialNote: "Rohan ale"
}
The problems come when you think how you store the answers, sort the questions, etc. Probably a collection called questions, with a field maybe called sortOrder, a field called tag, etc.
How did you pick up calling templates this way, rather than having them as html files that a router manages for you?
instead of just returning your json object with Questions.find().fetch() you could add another step to put your data into an array like:
test = function() {
var temp = [];
for (item in Questions.find().fetch()) {
temp.push(item);
};
return temp;
};
return test;
(sorry for not writing in coffee script, i'm not aware of the language abstraction)
To answer your question on how to do it, you can do something like this(in JS, sorry, not a coffeeScripter):
Template.Questionnaire.questions = function () {
var questions = [];
_.each(Object.keys(this), function (field) {
if(/^question.+/.test(field)) {
questions.push({ label: field, question: this[field]});
}
});
return questions;
};
And then in a template:
<template name="Questionnaire">
{{#each questions}}
<label>{{label}}</label>
<span>{{question}}</span>
{{/each}}
</template>
Something like that. But I agree with Jim Mack and that you should probably be storing this in an array.
Like as JIm Mack Posted, save your collection in an array
first of all insert your question in an array by doing these in your coffeescript:
x = document.getElementById('question-form')
length = x.length
i = 0
question = []
while i< length
aaa = x.elements[i]
question.push
questions: aaa
i++
then since you are using Jade-handlebars you need register helpers
in your jade file do these
{{#each arrayify myObject}}
{{#each this.name}}
p {{questions}}
{{/each}}
{{/each}}
The arrayify and myObject are the handlebars helpers. Then in your coffeescript
Handlebars.registerHelper "arrayify", (obj) ->
result = []
for temp in obj
userQuestion = temp.question
result.push
name: userQuestion
return result
Template.templatename.myObject = ->
temp = []
for item in Question.find().fetch()
temp.push item
return temp
Hope these will work.

javascript array in array

I am building a file management system for the web right now.
But I have some problems with javascript array's.
In the system there is an opportunity to add labels to file's.
In javascript I want to have the ID and the value's of the labels with the fileId in 1 array.(as below).
I also want the FileId and the LabelId not as the index of the array's. Because the FileId and labelId can be a realy high number. And then I have an array full of undefined items.
Here an example of how I would like to have it:
array[FileId][labelId,labelValue]
If you have an solution please help me.
Thanks.
You can form structure like this:
arr = [{FieldId:fid_value, Labels:[{labelId:lid_value, labelValue:label_text}]}]
Basically, an array with objects. Each object contains two fields: field id and labels.
Labels is an array with objects also. Each object has label id and label value property.
Code to create new items might be like this:
arr = array();
fieldObj = {FieldId:fid_value, Labels:[]};
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
...
arr.push(fieldObj);
I'm not entirely sure what you're asking but array within array is possible...
a = []
a.push('a')
Result:
["a"]
a.push(['hello','world'])
Result:
["a",
Array[2]
0: "hello"
1: "world"
]
It sounds like you want objects instead of arrays:
var obj = {};
obj["fieldName"] = {label: "labelname", labelId: 1234};
Then you can access this data as:
obj["fieldName"].label
You could also use an object
var data = {};
data["item1"] = { "labelId" : "foo1", "labelValue" : "bar1" };
data["item2"] = { "labelId" : "foo2", "labelValue" : "bar2" };
console.log(data.item1.labelId);
There are plenty of ways you can strcture the object, it is normally better to use an object than to remember that index 0 is the id and that index 1 is a value.
Use should use objects as well as arrays:
var root = [{
id: '12345',
metadata: {
label: 'foo',
},
type: 'folder',
name: 'Folder Name',
children: [...]
}
];
Now, you can iterate through the folders and files in your root:
for (var i = 0; i < root.length; i++) {
var item = root[i];
console.log(item.type, item.name, item.id);
}

finding information inside of nested arrays

I have an array that stores the values:
var array = [['favorite color'],['black','red']]
to get black I would:
document.write(array[0][1][0]);
then if i append to the array another question [['favorite thing']['box','ball']]
If I wanted ball I would:
document.write.array[1][1][1];
I am having trouble understanding arrays. I want an array with one question and multiple answers then I want to loop through them and display everything. I can do the loop but I am unsure how to find things in nested arrays once I create them.
Use a combination of objects (which work like dictionaries) and arrays. For example:
var array = [
{'question' : 'favorite color', 'choices' : ['black','red'] },
{'question' : 'favorite thing', 'choices' : ['box','ball'] }
]
for( var i = 0; i < array.length; i++ ) {
var question = array[i]['question'];
var choices = array[i]['choices'];
// here you can display / write out the questions and choices
}
Bearing in mind, creating a class and using a constructor or init methods would probably be better to encapsulate the idea of questions and answers. But the above is the basic idea.
var array = [['favorite color'],['black','red','blue']];
document.writeln(array[1][1]);
document.write(array[1][2]);
​
Would print red then blue see it working live : http://jsfiddle.net/HJ872/
How?
array[0] => gets an *array* = ['favorite color']
=> array[0][0] gets this first element `favorite color`
array[1] => also gets this array = ['black','red','blue']
=> and then [1][1] will get 'red', [1][2] will get `blue`

Categories