Array destructuring in LWC

Let's look at how to use Array Destructuring in LWC.

When we get data from Apex method processing it is one of the most important aspects of LWC.

It's a known fact that when we send a List from an Apex method we will receive it as an Array in LWC and when a Map is sent from Apex method an Object is received in LWC.

When we receive an Array in LWC not everything we might need all the elements of the Array and we might have to get a few elements out of it.

Let's look at how to get a few elements out of an Array using a concept in ES6 called Array destructuring.

In this class, we are sending all the values of a pick-list field Rating in Account object to Lightning Web Component.

public with sharing class LWCCustomDataTable {
  public LWCCustomDataTable() {
  }

  @AuraEnabled(cacheable=true)
  public static List<String> fetchRatingValues() {
    List<String> ratingOptions = new List<String>();

    Schema.DescribeFieldResult fieldResult = Account.Rating.getDescribe();
    List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();

    for (Schema.PicklistEntry a : ple) {
      ratingOptions.add(a.getValue());
    }
    ratingOptions.sort();
    return ratingOptions;
  }
}
LWCCustomDataTable.cls

In the LWC component if I were to fetch the first 2 items of the Array and assign it to a couple of local variables I will be using Array Destructuring (check the comments in the below code).

import { LightningElement, wire } from "lwc";

import getRatingValues from "@salesforce/apex/LWCCustomDataTable.fetchRatingValues";

export default class CustomDataTable extends LightningElement {
  @wire(getRatingValues)
  ratingValues({ error, data }) {
    if (data) {
    
      console.log(data); //[Cold, Hot, Warm]
      
      /* we are fetching only 2 elements of the array and 
      discarding others.*/
      let [cold, hot] = data;
      
      /* we are discarding the first element and fetching 
      2 elements of the array. */
      let [, hot1, warm1] = data;
      
    } else if (error) {
      console.log(error);
    }
  }
}
customDataTable.js

Hope that's helpful!