Sorting and Filtering Data from the Harry Potter API Using JavaScript

In the realm of web development, sorting and filtering data retrieved from API endpoints are common tasks that enhance data usability and readability. Imagine harnessing the magical world of Harry Potter to illustrate these concepts. In this post, we'll delve into the technical intricacies of sorting and filtering data from the Harry Potter API using JavaScript.

At the heart of our solution lies a set of JavaScript functions tailored to sort and filter JSON data. Let's dissect them:

  • isAnObject(item): This function checks whether a given item is an object, excluding arrays and null values.

  • sortObjectKeys(item): It sorts the keys of an object alphabetically and recursively sorts nested objects.

  • sortObjectsKeys(items): This function applies sortObjectKeys to each item in an array, filtering out non-object items.

Implementation:

To put these functions into action, we integrate them into an HTTP GET request handler, which fetches data from the Harry Potter API. Error handling ensures robustness, while parsing the JSON response prepares it for processing. Then, applying the sorting and filtering functions transforms the raw API data into a structured, organized format.

const isAnObject = (item) => typeof item === 'object' && item !== null && !Array.isArray(item);

 const sortObjectKeys = (item) => {
    return Object.keys(item)
    .sort()
    .filter(key => [null, undefined, ''].includes(item[key]) === false)
    .reduce((acc, key) => {
      acc[key] = isAnObject(item[key]) ? sortObjectKeys(item[key]) : item[key];
      return acc;
    }, {})
 };

 const sortObjectsKeys = (items) => {
  return items.map(item => {
    if (isAnObject(item)) {
      return sortObjectKeys(item);
    }
    return item;
  });
}

https.get('https://harry-potter-api-3a23c827ee69.herokuapp.com/api/characters', res => {
    let data = [];
    const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
    console.log('Status Code:', res.statusCode);
    console.log('Date in Response header:', headerDate);

    res.on('data', chunk => {
      data.push(chunk);
    });

    res.on('end', () => {
      console.log('Response ended: ');
      const users = JSON.parse(Buffer.concat(data).toString());

      console.log(
        'Response:', 
        sortObjectsKeys(users.slice(0, 6))
      );
    });
  }).on('error', err => {
    console.log('Error: ', err.message);
  });

Testing and Results:

Testing our solution with sample data from the Harry Potter API yields promising results. The sorted and filtered data exemplifies improved readability and organization compared to the raw API response. Each character's attributes are neatly arranged, enhancing the user's browsing experience.

Conclusion:

Sorting and filtering data from web APIs are invaluable skills in modern web development. By harnessing JavaScript's capabilities, we've demonstrated how to efficiently process data from the Harry Potter API, transforming it into a structured format ready for consumption. As you embark on your coding journey, remember the power of sorting and filtering in making data more accessible and user-friendly. Embrace these techniques, and let your code weave its own magic!