To iterate over the list in LWC there are two directives available.
n
for:each template directive nnTo render a list of items, use for:each directive or the iterator directive to iterate over an array. Add the directive to a nestednnThe iterator directive has first and last properties that let you apply special behaviors to the first and last items in an array.nnRegardless of which directive you use, you must use a key directive to assign a unique ID to each item. When a list changes, the framework uses the key to rerender only the item that changed. The key in the template is used for performance optimization and isn’t reflected in the DOM at run time.nnWhen using the for:each directive, use for:item=”currentItem” to access the current item. nn
nn n n n - n {contact.Name}, {contact.Title}n
n n
n nnnn
Ref: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_lists
// helloForEach.jsnimport { LightningElement } from 'lwc';nnexport default class HelloForEach extends LightningElement {n contacts = [n {n Id: 1,n Name: 'Amy Taylor',n Title: 'VP of Engineering',n },n {n Id: 2,n Name: 'Michael Jones',n Title: 'VP of Sales',n },n {n Id: 3,n Name: 'Jennifer Wu',n Title: 'CEO',n },n ];n}nn//Ref: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_listsn
2. iterator
n
To apply special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use the iterator directive on a template tag.
n
Use iteratorName to access these properties:
n
value—The value of the item in the list. Use this property to access the properties of the array. For example, iteratorName.value.propertyName.nindex—The index of the item in the list.nfirst—A boolean value indicating whether this item is the first item in the list.nlast—A boolean value indicating whether this item is the last item in the list.
n
Checkout the sample as below:
n n n n - n n {it.value.Name}, {it.value.Title}n n
n n
n nn
n
.list-first {n border-top: 1px solid black;n padding-top: 5px;n}nn.list-last {n border-bottom: 1px solid black;n padding-bottom: 5px;n}n
Ref: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_lists
n
#LWC