I’m building a search suggestion system that connects to a music streaming service API to fetch playlist data. The API call works fine, but sometimes the returned array contains empty entries mixed with valid ones. These empty entries cause my application to crash when I try to access their properties.
The main issue is that I get errors like Cannot read properties of null (reading ‘name’) when processing the results. Even if I check for the ‘name’ property, I still get similar errors for other fields like ‘images’ or ‘owner’. I think the best approach would be to filter out these empty entries completely before processing, but I’m not sure about the best way to do this.
Here’s my current implementation:
// Search autocomplete functionality
$(document).ready(function() {
$("#search-input").autocomplete({
source: function(query, callback) {
const token = "<?php echo $_SESSION['api_token'] ?>";
$.ajax({
url: "https://api.example-music.com/v1/find",
headers: {
"Authorization": "Bearer " + token
},
data: {
query: query.term,
category: "playlist",
max_results: 8
},
success: function(response) {
// How can I remove null entries from response.collections.items here?
if (response.collections && response.collections.items) {
const collections = response.collections.items.map(function(item) {
return {
text: item.title,
val: item.title,
uid: item.uid,
photos: item.photos,
creator: item.creator.username
};
});
callback(collections);
} else {
callback([]);
}
},
error: function(req, status, err) {
console.log("API request failed:", err);
callback([]);
}
});
},
minLength: 2,
select: function(evt, selected) {
console.log("Chosen item:", selected.item.uid);
$("#selected-id").val(selected.item.uid);
}
});
});
What’s the proper way to clean up the array and remove those null entries before mapping?