Reputation: 184
With the following code:
req.Course.find({}).populate('students', 'username firstName lastName registered').populate('teacher', 'image mID firstName lastName').sort({title: 1}).exec(function(err, courses){
if(err) throw err;
req.toJade.courses = [];
if (courses){
req.toJade.courses = advs;
}
res.render('courses/list', req.toJade);
});
courses
is an array of objects in the following format:
[{
_id: objectid,
title: 'History',
teacher:
{
_id: objectid,
name: 'John Smith',
etc...
},
etc...
},
etc...
]
I loop through the array of those objects in Jade with and when I try to access a property of any teacher with
for c in courses:
h1= c.title
small= c.teacher.name
it returns an error that it cannot read property 'name' of undefined. And this occurs when I try to access any other property of the course object.
However, using
for c in courses:
h1= c.title
small= c.teacher
prints out the whole clearly defined object with the all of its properties existing and with the correct values.
What am I doing wrong and how can I access any of the properties of the teacher objects?
Upvotes: 1
Views: 94
Reputation: 27843
for..in
iterates over all properties of an object. In the case of Arrays, this means all of its values, all of the properties set on the array itself and all of the properties set on Array.prototype
. Usually when dealing with Arrays you are only interested in the values, so for..in
is not the best choice.
The proper way to iterate over Array values is by using a a simple for/while/do while
or by using Array#forEach
and other similar functional iteration methods:
for (var i=0; i<courses.length; i++) {
var c = courses[i];
h1 = c.title;
small = c.teacher.name;
}
// or
courses.forEach(function(c){
h1 = c.title;
small = c.teacher.name;
});
Also, a simple wayto avoid the error if the teacher property is not set would be:
small = c.teacher && c.teacher.name;
If c.teacher
is undefined
, small
will be undefined
as well, otherwise it will be equal to c.teacher.name
.
Adding a default value is just as easy:
small = c.teacher && c.teacher.name || 'Unknown teacher';
Upvotes: 2
Reputation: 687
java script will check for the existence of properties for a particular object only when we access it. Because it is not typed language as C#,Java. In java script we can add or remove properties dynamically.
To check for the existence of a property in an object we can use the function which is available for all the objects in javascript.
objectname.hasOwnProperty("propertyToCheck")
Upvotes: 2
Reputation: 184
I have found my dumb mistake. I wasn't expecting 2 objects in the courses array to have their teacher as undefined. I guess that broke the whole thing since I never checked to see if the teacher property exists.
Upvotes: 1