Working with collection in jasascript

Fermin Perdomo Fermin Perdomo
schedule 1 min read
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); });

Reactions

lock You need to be logged in to react.
Log In

Newsletter

Get new posts delivered straight to your inbox.

mail

Great Tools for Developers

Git Tower

Git Tower

A powerful Git client for Mac and Windows that simplifies version control.

Visit arrow_forward
Mailcoach

Mailcoach

Self-hosted email marketing platform for sending newsletters and automated emails.

Visit arrow_forward
Uptimia

Uptimia

Website monitoring and performance testing tool to ensure your site is always up and running.

Visit arrow_forward
Cloudways

Cloudways

Managed cloud hosting platform that simplifies server management for developers.

Visit arrow_forward

Comments

No comments yet. Be the first to share your thoughts.

chat_bubble Join the conversation — log in to leave a comment.
Log In