Reputation: 355
I have a simple Cheerio parse i'm doing on a request app. Not sure why this undefined error is coming up when trying to set the array but i'm guessing the value isn't there for it to set.
var $ = cheerio.load(body);
var json = [
{ "range": "", "address": "", "state": "", "zip": "", "info": "" }
];
$('.findCourse').each(function (i, elem) {
// Range Name
console.log("iteration - ", i);
console.log("name - ", $(this).text().trim());
json[i].range = $(this).text().trim();
});
Here is my console response with it reading and setting the first two items it finds in the scraped html.
iteration - 0
name - Pollock's Ferry Hunting Club Inc.
iteration - 1
name - Eagle 1
TypeError: Cannot set property 'range' of undefined
at Object.<anonymous> (/usr/local/node_app/server.js:30:31) at exports.each (/usr/local/node_app/node_modules/cheerio/lib/api/traversing.js:267:24) at Request.request.post.form.__EVENTTARGET [as _callback] (/usr/local/node_app/server.js:26:30) at Request.self.callback (/usr/local/node_app/node_modules/request/request.js:121:22) at Request.EventEmitter.emit (events.js:98:17) at Request.<anonymous> (/usr/local/node_app/node_modules/request/request.js:978:14) at Request.EventEmitter.emit (events.js:117:20) at IncomingMessage.<anonymous> (/usr/local/node_app/node_modules/request/request.js:929:12) at IncomingMessage.EventEmitter.emit (events.js:117:20) at _stream_readable.js:920:16 1 May 23:02:57 - [nodemon] app crashed - waiting for file changes before starting...
Upvotes: 1
Views: 23480
Reputation: 355
Found the issue. The debugging statements were being executed before the reference error was thrown.
Simple javascript array issue where I was trying push the new element into the array at a position that didn't exist.
Here is my fix.
var $ = cheerio.load(body);
var json = [];
$('.findCourse').each(function (i, elem) {
// Range Name
json.push({});
json[i].range = $(this).text().trim();
});
Upvotes: 8