Fermin Perdomo
Full Stack Developer
© 2025 Fermin's Portfolio | All rights reserved.
Working with collection in jasascript
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.
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);
});