Destructuring Objects in LWC

Just like how we can destructure arrays in LWC we can also destructure objects in LWC. Let's look at how to do it.

Just like how we can destructure arrays in LWC we can also destructure objects in LWC.

Let's look at how can we use it for our good in a Lightning Web Component.

This snnipet here is making a callout using fetch API in the Lightning Web Component.

Here is the sample response from the endpoint

We are using destructuring in one of the callbacks to extract the value for the key repos_url from the response that we get back which is typically an array of objects (where each object is some info about the repo).

Here is the snippet!

 import { LightningElement } from "lwc";

export default class ExploreFetch extends LightningElement {
  constructor() {
    super();
    let endPoint = "https://api.github.com/users/technoweenie/orgs";
    fetch(endPoint)
      .then((response) => response.json())
      .then((repos) => {
        //mapping through all the entries in a map
        let repoList = repos.map((repo) => {
          //destructuring to extract value for key repos_url
          let { repos_url } = repo;
          return repos_url;
        });
        console.log(repoList);
      });
  }
}

exploreFetch.js
Response from the callout!

Hope this was helpful!