CodeBlanks Logo Icon CodeBlanks

Summary - Destructuring

JavaScript course · Advanced · Lesson 29/100

Write a function that parses an API response using destructuring.

Summary - Destructuring

In this group you learned five destructuring essentials: object and array patterns, default values, renaming and nested patterns. Now we combine them to parse API responses.

There are two tasks: first you will pull a user list and a total count out of an API response; then you will write a function that destructures the response it receives as a parameter. Defaults and nested patterns will come in handy here.

Exercise Parse an API response

Create a response object. It should hold data (an object that holds a users array) and meta (an object that holds a total property). Use destructuring to move users into userList and pull out total. Then log userList and total separately with console.log.

Show example solution
const response = {
  data: { users: ["Alex", "Sam"] },
  meta: { total: 2 }
};
const { data: { users: userList }, meta: { total } } = response;
console.log(userList);
console.log(total);

Exercise Write an API response parser

Write a function called parseApiResponse(response). It takes an API response object as a parameter. Inside the function body, use destructuring to pull out status with a default of "ok"; also pull the items array from inside the data property. Return the first item of items.

Show example solution
function parseApiResponse(response) {
  const { status = "ok", data: { items } } = response;
  return items[0];
}

Test yourself

  1. Match all the concepts

    object pattern
    Curly braces, by name
    array pattern
    Square brackets, by order
    default
    Fallback for undefined
    renaming
    New name with a colon
    nested pattern
    Deep property in one step
  2. Pull users out of an API response

    const apiResponse = { data: { users: ["Alex"] } };
    const { data: { users } } = ____;
    console.log(users);
    Show answer
    const apiResponse = { data: { users: ["Alex"] } };
    const { data: { users } } = apiResponse;
    console.log(users);

All lessons in Advanced