Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

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.

By Teja, ex-Salesforce engineer · Updated March 21, 2021 · 1 min read

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.

[
  {
    "login": "lostisland",
    "id": 2613464,
    "node_id": "MDEy0k9yZ2FuaXphdGlvbjI2MTMONjQ=",
    "url": "https://api.github.com/orgs/lostisland",
    "repos_url": "https://api.github.com/orgs/lostisland/repos",
    "events_url": "https://api.github.com/orgs/lostisland/events",
    "hooks_url": "https://api.github.com/orgs/lostisland/hooks",
    "issues_url": "https://api.github.com/orgs/lostisland/issues",
    "members_url": "https://api.github.com/orgs/lostisland/members{/member}",
    "public_members_url":
    "https://api.github.com/orgs/lostisland/public_members{/member}",
    "avatar_url": "https://avatars.githubusercontent.com/u/2613464?v=4",
    "description": null
  }
]

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

["https://api.github.com/orgs/lostisland/repos"]

Response from the callout!

Hope this was helpful!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts