Sub topic 9
Preparing display values in JavaScript
This chapter assumes you can write an LWC component with an HTML template and a JavaScript class, bind properties with curly braces, and use map on arrays. It also assumes you know for:each and keys from earlier chapters.
Why templates need prepared data
An LWC template binds to properties and getters. It cannot run expressions. You can't write {contact.Id === selectedId ? 'selected' : ''} in the HTML, and you can't call a function with an argument inside a binding. Anything the template needs to display must already exist as a value on the object you are iterating.
The standard fix is to build a new array in JavaScript. Each element is a copy of the original item with extra fields added. The template then reads those fields as plain properties.
Adding fields with a getter and map
A getter runs each time the component renders, so its result follows the current state. The getter below copies each contact and adds a cssClass field.
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
selectedId;
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
get hasContacts() {
return this.contacts.length > 0;
}
get decoratedContacts() {
return this.contacts.map((contact) => ({
...contact,
cssClass: contact.Id === this.selectedId ? 'selected' : ''
}));
}
handleSelect(event) {
this.selectedId = event.currentTarget.dataset.id;
}
}The spread syntax ...contact copies every existing field into the new object. The new cssClass field is added after it. The original contacts array is not changed.
Using the prepared data in the template
The template iterates over decoratedContacts instead of contacts. It reads contact.cssClass directly and shows a fallback when the list is empty.
<template>
<ul lwc:if={hasContacts}>
<template for:each={decoratedContacts} for:item="contact">
<li key={contact.Id}
class={contact.cssClass}
data-id={contact.Id}
onclick={handleSelect}>
{contact.Name}
</li>
</template>
</ul>
<p lwc:else>No contacts to show.</p>
</template>Three things happen here:
hasContactsis a getter that returns a boolean, solwc:ifneeds no expression.key={contact.Id}still uses the original identifier. The spread keepsIdon the new object, so the key stays stable between renders.data-idstores the Id so the click handler can find out which item was clicked.
How the update flows
When the user clicks an item, handleSelect assigns selectedId. The component re-renders, the getter runs again, and only the matching item gets selected.
Choosing what to compute
Compute these values in JavaScript:
| Need | Prepared field |
|---|---|
| Conditional CSS class | `cssClass` |
| Formatted date or currency text | `displayDate` |
| Boolean flag for `lwc:if` on each item | `isActive` |
| Combined text such as a full name | `fullName` |
Common mistakes
- Mutating the original objects. Writing
contact.cssClass = ...insidemapchanges the source data. Return a new object instead. - Dropping the key field. If you build the new object from scratch and forget
Id, the key becomesundefined. Spread the original or copyIdexplicitly. - Using the index as the key. Prepared data does not change this rule. Keep the stable identifier from the record.
Exercise
Exercise
A developer adds isSelected to each contact by writing this.contacts.forEach(c => { c.isSelected = c.Id === this.selectedId; }) inside a getter, then returns this.contacts. Why is map with a spread a better choice?
Show answer
The forEach version mutates the original objects, so the source data is changed every time the getter runs. Using map with ...contact returns new objects with the extra field and leaves this.contacts unchanged.
Exercise
Write a getter named labeledContacts that returns each contact with a label field equal to Name followed by ( and Id and ). What must you make sure the new objects still contain so the template key works?
Show answer
get labeledContacts() { return this.contacts.map((contact) => ({ ...contact, label: ${contact.Name} (${contact.Id}) })); } The spread keeps the Id field, which the template uses as the key.