Iterate/loop List using For:Each in LWC

In Lightning web components, we can iterate or loop through list of elements using for: each directives.

Iterate Using For Each Loop in LWC

Here is sample code for for: each 

<template for:each={fruitsList} for:item="fruit">
	<li key={fruit}>
		{fruit}
	</li>
</template>

here,

  • for:each: will take list of items to iterate
  • for:item: current item in that list, you can name it anything
  • Key: To assign a key to the first element

IterateUsingForEach.html

<template>
    <lightning-card title="Iterate using For Each" icon-name="custom:custom14">
        <ul class="slds-m-around_medium">
            <template for:each={fruitsList} for:item="fruit">
                <li key={fruit.Id}>
                    {fruit.Id}. {fruit.Name}
                </li>
            </template>
        </ul>
    </lightning-card>
</template>

IterateUsingForEach.js

import { LightningElement } from 'lwc';

export default class IterateUsingForEach extends LightningElement {
    // Creating an array with some data
    fruitsList = [
                    {
                        Id: 1,
                        Name: "Apple"
                    },
                    {
                        Id: 2,
                        Name: "Banana"
                    },
                    {
                        Id: 3,
                        Name: "Mango" 
                    },
                    {
                        Id: 4,
                        Name: "Orange" 
                    }
                ];
}

IterateUsingForEach lwc Output:

for-each-loop-lwc

Also found above code in Tech Shorts Git repo

Source:
https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.create_lists

Labels:
LWC
Join the conversation