Skip to main content

How to Use JavaScript Sets and Maps in Salesforce LWC

In plain words: A Set is a collection of unique values used to remove duplicates, while a Map is a collection of key-value pairs used for fast data lookups. Because Salesforce Lightning Web Components (LWC) are built on modern JavaScript (ES6), you can use native Sets and Maps directly in your controller files to write cleaner, more efficient code.

When manipulating data in Salesforce Lightning Web Components (LWC), developers often rely heavily on standard Arrays and Objects. However, modern JavaScript provides two highly optimized data structures that can make your code significantly better: Sets and Maps.

Whether you need to extract a list of unique Record IDs or map Account names to their respective revenue numbers, knowing how to leverage Sets and Maps will instantly elevate your LWC development skills.

1. Understanding Sets in LWC

A Set is a special type of collection where every value must be completely unique. If you try to add a duplicate value into a Set, JavaScript simply ignores it. This makes Sets the ultimate tool for deduplicating arrays.

Real-Life Example: Imagine you query a list of 50 Contacts, and you want to extract just the unique AccountIds so you can perform another query. Passing those 50 IDs into a Set will automatically filter out the duplicates, leaving you with just the unique Account IDs.
// 1. Initialize a new Set
let fruitSet = new Set();

// 2. Add values
fruitSet.add('Apple');
fruitSet.add('Banana');
fruitSet.add('Apple'); // This duplicate is safely ignored!

// 3. Check if a value exists (Returns true/false)
let hasApple = fruitSet.has('Apple'); 

// 4. Remove a value
fruitSet.delete('Banana');

// 5. Iterate over the remaining items
for (let fruit of fruitSet) {
    console.log(fruit); // Output: Apple
}

2. Working with Maps in LWC

A Map is an ordered collection of key-value pairs. While standard JavaScript Objects also store key-value pairs, Maps offer distinct advantages: they remember the exact order in which you inserted the items, and they allow any data type to be a key (even an entire object or function), whereas standard Objects only allow Strings and Symbols as keys.

// 1. Initialize a new Map
let userMap = new Map();

// 2. Set key-value pairs
userMap.set('Name', 'John Doe');
userMap.set('Age', 30);
userMap.set('Role', 'Admin');

// 3. Retrieve a specific value using its key
let userName = userMap.get('Name'); // Output: 'John Doe'

// 4. Check if a key exists
let hasAge = userMap.has('Age'); // Output: true

// 5. Delete a key-value pair
userMap.delete('Role');

// 6. Iterate through the Map
for (let [key, value] of userMap) {
    console.log(`${key}: ${value}`); 
    // Output: 
    // Name: John Doe
    // Age: 30
}
Developer Trap: JSON Stringification
Be careful when passing data back to Apex or trying to display it directly in your HTML template. JSON.stringify() does not work on Maps and Sets out of the box! If you need to send a Map or Set to Apex, you must convert it into a standard Array or Object first. For example, to convert a Set to an array: Array.from(mySet).

3. Integrating Sets and Maps in Your Component

Here is a practical example of combining a Set and a Map inside an LWC lifecycle hook. We use a Set to store unique items, and then we use a Map to store those items as keys along with the length of their names as the values.

import { LightningElement } from 'lwc';

export default class DataStructuresDemo extends LightningElement {
    
    connectedCallback() {
        // Create a Set directly with an array of items (duplicates automatically removed)
        let uniqueFruits = new Set(['Apple', 'Banana', 'Apple', 'Cherry']);
        
        // Initialize an empty Map
        let fruitLengthMap = new Map();

        // Loop through the unique Set and populate the Map
        for (let fruit of uniqueFruits) {
            fruitLengthMap.set(fruit, fruit.length);
        }

        // Test the lookup speed of the Map
        let bananaLetterCount = fruitLengthMap.get('Banana'); 
        console.log(`Banana has ${bananaLetterCount} letters.`); // Output: 6
    }
}
360 Card: When to use which?
  • Standard Array: When you just need a simple, ordered list of items.
  • Set: When you have a list of items but need to guarantee there are zero duplicates.
  • Standard Object: When you need a simple dictionary with string-based keys to pass to an HTML template or Apex.
  • Map: When you need a dictionary that preserves insertion order, requires complex keys, or requires frequent additions/deletions.
Core Takeaway: To optimize data parsing in LWC, use Sets to instantly remove duplicate values from API responses, and use Maps to create high-speed data lookup tables.

Conclusion

Sets and Maps are incredibly powerful JavaScript ES6 features that come natively baked into the Lightning Web Components framework. By replacing cumbersome for loops and conditional checks with native Set and Map methods, you can write code that is not only faster to execute but also much easier to read and maintain.

Happy coding!