Filter out empty entries from music streaming API response array

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?

try using optional chaining if you’re on a newer js version - item?.creator?.username prevents those annoying null errors. combine it with a simple filter like items.filter(item => item?.title && item?.uid) before mapping

just add a filter before your map call to clean out the junk. something like response.collections.items.filter(item => item && item.title && item.creator) should do the trick. works for me when dealing with spotty api responses

The issue you’re encountering is pretty common with music APIs. I’ve dealt with similar problems when working with playlist endpoints that sometimes return partial or corrupted data. Instead of just checking for the existence of the item itself, you need to validate all the nested properties you’re actually using in your mapping function. In your case, since you’re accessing item.creator.username, you should also verify that the creator object exists before proceeding. Try filtering with something like response.collections.items.filter(item => item && item.title && item.uid && item.creator && item.creator.username). This way you’re ensuring all the properties your map function expects are actually present. I learned this the hard way after getting intermittent crashes in production. The APIs sometimes return items with missing nested objects even when the parent item looks valid at first glance.

I ran into this exact same problem when integrating with a music API last year. The tricky part is that null entries can appear at different levels of nesting, not just at the root item level. What worked reliably for me was creating a helper function to validate the complete structure before filtering. You can do something like const isValidItem = (item) => { return item && item.title && item.uid && item.photos && item.creator && typeof item.creator.username === 'string'; } then use response.collections.items.filter(isValidItem) before your map call. This approach saved me from numerous edge cases where items had some properties but were missing others. The key insight is that APIs sometimes return placeholder objects with null values rather than completely empty entries, so checking each required property individually prevents those sneaky runtime errors.