I have a few jQuery plugins that I made – all parse JSON feeds and render them using Mustache.js; each plugin takes an integer value of how many items to display.
I received a Uncaught TypeError: Cannot read property 'link' of undefined when trying to parse the Stack Overflow JSON feed with the following code:
$.ajax({
type: 'GET',
url: query,
contentType: "jsonp",
dataType: 'jsonp',
success: function (jsonp) {
/* loop through JSON items converting the time from UNIX timestamp
** format to readable words by parsing it through timeConverter() */
var i;
for (i = 0; i < jsonp.items.length; i++) {
if (i > num-1){
delete jsonp.items[i];
} else {
jsonp.items[i].creation_date = timeConverter(jsonp.items[i].creation_date);
}
}
var output = Mustache.render(must_template, jsonp);
element.html(output);
return element;
} //EOF CALLBACK
}); //EOF AJAX
As a quickfix I disabled the truncation by simply commenting out the delete operation. The error suggests that Mustache.js is trying to access part of the JSON object which no longer exists; yet the delete operation clearly only affects items which are above the user-defined limit.
When this behaviour occured there were still 20 items in the array.
Note:
Yes, I’ve answered this question myself; however – I’m more than willing to accept another answer if it shows best practice, a neater way or improves upon my answer in some way. 🙂
deleteis a “lower-level” operator compared to arrays. It directly removes the object property, bypassing all the specific array logic and hence does not update the length of the array.If you want to delete an element from an array, use either
.splice[MDN], or in your case you can simply set the length of the array and iterate over the remaining elements afterwards: