JSON / Jade - Cannot output JSON variable to Jade template - javascript

I'm passing some JSON data to a Jade template, but can't seem to print the JSON data to my Jade template. This is an example of the JSON which is stored and passed to the Jade template:
{ name: 'Team 1',
_id: 5134d71192cf972226000003,
__v: 0,
key: 1362417425623 }
It is passed through to the Jade template like so:
res.render('tournamentDetails', { 'tournamentData' : tournamentData, seedsSerialized : JSON.stringify(tournamentData.teams) } );
The format of the Jade template is:
script(type='text/javascript')
var seeds = [#{tournamentData.teams}];
I'm trying to access this variable seeds in a seperate JavaScript file, but cannot seem to access them. I have been testing using alert to test what is in seeds in the JavaScript file and it is not the teams.
This is the generated HTML from the Jade too:
var seeds = [{ name: 'Team 1',
_id: 5134d71192cf972226000003,
__v: 0,
key: 1362417425623 },{ name: 'Team 2',
_id: 5139dc66b48da58d0e000001,
__v: 0,
key: 1362746470498 },{ name: 'Team 3',
_id: 5139dda45f1598440f000001,
__v: 0,
key: 1362746788314 },{ name: 'Team 4',
_id: 513b2c66cfd50dce11000001,
__v: 0,
key: 1362832486554 }];
How would I access the teams in a JavaScript file? I am wanting to output the names of the teams to the Jade template.

This may not be an answer exactly, but it was too long for a comment...
Look at this jsfiddle: http://jsfiddle.net/KvXTA/
var seeds = [{ name: 'Team 1',
_id: 5134d71192cf972226000003,
__v: 0,
key: 1362417425623 },{ name: 'Team 2',
_id: 5139dc66b48da58d0e000001,
__v: 0,
key: 1362746470498 },{ name: 'Team 3',
_id: 5139dda45f1598440f000001,
__v: 0,
key: 1362746788314 },{ name: 'Team 4',
_id: 513b2c66cfd50dce11000001,
__v: 0,
key: 1362832486554 }];
console.log(seeds);
notice how the console outputs
Uncaught SyntaxError: Unexpected token ILLEGAL
That's because of the _id fields. I'm surprised you say that the serialized version has the same problem, since it should have surrounded the ID's in quotes. If you don't need the ID's at all, you can get rid of them in the serialized version by using a replacer function.
var seedsSerialized = JSON.stringify(teams, function (key, val) {
return key === '_id' ? undefined : val;
);
res.render('tournamentDetails', { seedsSerialized: seedsSerialized });
Then use that serialized version to initialize seeds in the template.
script
var seeds = !{seedsSerialized};
My earlier comment about order of including scripts wasn't a concern that maybe another file was creating a seeds variable, it was that you might have been including a file which used seeds before seeds was actually declared.
For example:
<script src='logSeeds.js'></script>
<script>
var seeds = [ ... ];
</script>
where logSeeds.js is:
console.log(seeds);
would obviously output undefined since seeds hasn't been declared yet. It was just a thought, not necessarily your situation.

Related

Separate big array from main component to a new file

I'm new in the front end world, and I currently working on Angular project with typescript, and I created an array in order to assign to an object, so I have something like this in my TS component:
formOptions = []
ngOnInit() {
this.formOptions = [{
id: 1,
description: 'First name'
},
{
id: 2,
description: 'Middle name'
}, {
id: 3,
description: 'Last name'
}...etc
}
As you can see the array it's going to be supper big, is there a way to move the array to separate file, then import it and just assign the object? If so, where is the common path to save this path of files and what extension I should use for it?
Try storing the array in a separate .json file. Then use fetch to load the file and parse the JSON. JSON is Javascript Object Notation and it will take an array (or object) exactly as you have it laid out in your code.
[{
id: 1,
description: 'First name'
},
{
id: 2,
description: 'Middle name'
}, {
id: 3,
description: 'Last name'
}...etc
}]
The first example at MDN does exactly what I describe.

Why is my JSON object showing [Array] instead of the data in javascript after reformatting?

Currently I am trying to create a JSON object in java script which has an additional array containing all of the data that I currently posses:
src is a JSON object which before any code is run is equal to:
[
{
_id: new ObjectId("629ac43586b27bfd70337d06"),
Title: 'Test Poll',
Option: [ 'Test Option 1', 'Test Option 2', 'Test Option 3' ]
},
{
_id: new ObjectId("629afc9286b27bfd70337d09"),
Title: 'Test Poll 2',
Option: [ 'Test Option 1' ]
}
]
I need to reformat this object so that it is contained within a separate array which I am currently attempting to do with this line:
var context = { poll:src };
This results in a reformatting of the JSON object which I do not understand, after running this code context contains:
poll: [
{
_id: new ObjectId("629ac43586b27bfd70337d06"),
Title: 'Test Poll',
Option: [Array]
},
{
_id: new ObjectId("629afc9286b27bfd70337d09"),
Title: 'Test Poll 2',
Option: [Array]
}
]
It gets rid of the Option arrays and replaces them with [Array]. I need to keep these arrays and I am not sure what to change to fix this as I have tried looking elsewhere for answers. Does anyone have an idea of what is going on here?
Ok they are arrays I am just too new to realize that it would not print fully. I was attempting to use handlebars on these Option arrays to print the list and I was forgetting to use the implicit this for the variable name instead of just 'Option'.
Problem solved.

Validating values in YAML files across collection

I'm using Node (https://eemeli.org/yaml/) to parse a YAML configuration files which looks like so:
items:
- name: item 1
value: 25
- name: item 2
value: 25
- name: item 3
value: 50
What I'd like to do is assert the value numbers all add up to 100 when parsing the document.
Should I be running this validation after parsing the YAML
eg:
data = YAML.parse(recipe)
validate(data)
Or is there a better way of doing this using the YAML library directly when loading the document?
Thanks in advance for your help!
You're better of parsing the YAML first, then going through the resulting data. So, in this case, the parsed data would look something like:
data = {
items: [
{name: 'item 1', value: 25},
{name: 'item 2', value: 25},
...
]
}
So, you can just loop through the values:
let total = 0;
data.items.map((item) => {
total += item.value;
});
if (total !== 100) {
...
}

Efficient algorithm / recursive function to nest items from a list

I'm currently implementing my own commenting system. Unfortunately Disqus or any other comment platform doesn't meet my requirements.
I use NodeJS and MongoDB as backend. I need to run basically two queries on my database:
Get all comments by a topic/slug
Get all comments by a user
One can comment to an topic or reply to a comment.
Hey, cool post # top lvl comment
Thanks! # reply to comment
Foo Bar! # reply to reply
and so on...
So my database schema looks like
{
id: ObjectId,
text: string,
author: { id: ObjectId, name: string },
parent: nullable ObjectId,
slug: string/number/whatever
}
If parent is null it's a top level comment, otherwise it's a reply.
Pretty easy so far, right? The problem I do have now is displaying comments below posts. When there would be only top level comments it would be easy. Just get all comments for one specific slug, sort them by date/rating/... and compile them with my HTML View Engine.
But there are in fact replies and I'm just stuck at the point where I need to organize my structure. I want to nest replies into comments within my list
Original list (simplified)
[
{ id: 1, text: 'foo', parent: null },
{ id: 2, text: 'bar', parent: 1 },
// ...
]
Expected Output
[
{ id: 1, text: 'foo', replies: [
{ id: 2, text: 'bar' },
] },
]
I've tried creating my expected output with a recursive function which got very weird tho. Unless that it wouldn't be very efficient. So since I'm really getting frustrated and kinda feeling stupid not solving this problem I've decided to ask for your help SO.
The actual problem I want to solve: How do I render my comments, that they are properly nested etc.
The question I'm going to ask: How do I organize my flat structure in an efficient way to solve the above described problem?
Here's one approach with linear complexity:
var comments = [{
id: 3,
text: 'second',
parent: 1
}, {
id: 1,
text: 'root',
parent: null
}, {
id: 2,
text: 'first',
parent: 1
}, {
id: 5,
text: 'another first',
parent: 4
}, {
id: 4,
text: 'another root',
parent: null
}];
var nodes = {};
//insert artificial root node
nodes[-1] = {
text: 'Fake root',
replies: []
};
//index nodes by their id
comments.forEach(function(item) {
if (item.parent == null) {
item.parent = -1;
}
nodes[item.id] = item;
item.replies = [];
});
//put items into parent replies
comments.forEach(function(item) {
var parent = nodes[item.parent];
parent.replies.push(item);
});
//root node replies are top level comments
console.log(nodes[-1].replies);

How to access a specific index of an array in node.js

I want to get only the AID from the solution now i am getting. I tried rows[0] but was not successful.
Code:
console.log('The solution is: ', rows);
Output:
The solution is:
[ { AID: 6520,
DID: 113071,
TITLE: 'First Knight',
DATE: '7/7/1995',
SCORE: 89 } ]
Use rows[0]["AID"] to access the AID property.
Let's understand your overall data structure here:
var rows = [
{
AID: 6520,
DID: 113071,
TITLE: 'First Knight',
DATE: '7/7/1995',
SCORE: 89
}
];
The variable rows is an array of objects. Thus rows[n] gets you a specified object in that array and therefore rows[0] is the first object in the array which would be:
{
AID: 6520,
DID: 113071,
TITLE: 'First Knight',
DATE: '7/7/1995',
SCORE: 89
}
So, now you want to access the AID property in that object so you can just do:
rows[0].AID
And, here's a working snippet demo:
var rows = [
{
AID: 6520,
DID: 113071,
TITLE: 'First Knight',
DATE: '7/7/1995',
SCORE: 89
}
];
document.write(rows[0].AID);

Categories

Resources