Reputation: 133
I'm new to Express and Jade, can't find why Jade tells me the object is undefined. I've a big JSON file about a collectionable card game, which structure is:
{
"LEA" : { /* set data */ },
"LEB" : { /* set data */ },
"2ED" : { /* set data */ },
...
}
and, for each set
"name" : "Nemesis",
"code" : "NMS",
"gathererCode" : "NE",
"oldCode" : "NEM",
"magicCardsInfoCode" : "ne",
"releaseDate" : "2000-02-14"
"border" : "black",
"type" : "expansion",
"block" : "Masques",
"onlineOnly" : false,
"booster" : [ "rare", ... ],
"cards" : [ {}, {}, {}, ... ]
I want to loop through the array of cards for a GETed set and display some informations about. This is my cards.js
file
'use strict';
var express = require('express');
var router = express.Router();
var mtgjson = require('mtgjson');
router.get('/:set?', function(req, res){
var set = req.params.set;
if (set === undefined) {
res.send('respond with a resource');
} else {
mtgjson(function(err, data) {
if (err) return console.log(err);
res.render('cards', { selectedSet : data.set });
});
}
});
module.exports = router;
and this the jade template
extends layout
block content
h1 #{selectedSet.name}
ul
each card in selectedSet.cards
li #{card.rarity}
I'm getting
Cannot read property 'name' of undefined
Any suggestion will be much appreciated, I'm probably making some stupid error.
EDIT: New informations ------------------
When I console.log(data)
I get the following, it seems right:
TOR:
{ name: 'Torment',
code: 'TOR',
magicCardsInfoCode: 'tr',
releaseDate: '2002-02-04',
border: 'black',
type: 'expansion',
block: 'Odyssey',
booster:
[ 'rare',
'uncommon',
...
'common' ],
cards:
[ [Object],
[Object],
[Object],
...
[Object],
[Object],
[Object] ] },
And if I console set
It gives me the right string ( TOR in this example ).
Edit 2 -------------------------
If I pass the entire data
object and the set
variable to the jade template, I can achieve the final result but in a very sub-optimal way.
I've made something like this
block content
ul
each val, key in data
if key == set
li #{val.name}
each card in val.cards
p #{card.name}
SOLUTION ----
Just a stupid error: I just messed up with property accessors. I should use data[set]
instead of data.set
beacause var set
is a literal.
See reference http://www.ecma-international.org/ecma-262/5.1/#sec-11.2.1
Upvotes: 0
Views: 98
Reputation: 133
I was using the wrong notation to access properties. I should use square brackets notation beacause the var set
is a string literal, in this case the dot notation won't work.
See reference
Upvotes: 0
Reputation: 101
You need to use selectedSet.cards.rarity
instead of cards.rarity
. The only object you are passing to the template is your selectedSet
object, and cards
is nested within that.
Upvotes: 0