How to use foreach loop with the array and objects in knockout js magento?

knockout Javascript with Foreach loops for the observable array and objects with the data-bind property of the DOM tag.

Let’s start with a simple for each loop with an array that contains the numbers only,

JS file contains the knockout declaration of the observable array, called getNumbers property,

define([
    'uiComponent',
    'ko'
], function (Component, ko) {
    'use strict';

    return Component.extend({
        getNumbers: ko.observableArray([2,4,6,8,10]),
        getCountryCurrency: ko.observableArray([
                {
                    country: 'United State',
                    currency: 'USD',
                    rate: 1.0
                },
                {
                    country: 'England',
                    currency: 'EUR',
                    rate: 1.5
                },
                {
                    country: 'India',
                    currency: 'INR',
                    rate: 2
                }
            ]
        )
    });
});

Here in the file,
getNumbers: ko.observableArray([2,4,6,8,10])
Now we will get the number using knockout for each syntax,

<ul data-bind="foreach: getNumbers">
    <li data-bind="text: $data"></li>
</ul>

Here Knockout syntax for the looping the array is data-bind=”foreach:  methodName”.

$data parameter used to get the current value from the array in Magento.

For the simple array, We will fetch the array value using text binding(data-bind=”text: $data”) or i18n binding(data-bind=”i18n: $data”). text binding is used to print text value of the parameter in knockout.

When the first time loop iterates, it will be getting the first value from the array, and then based on the sequence it will iterate over the entire array.

    • Complex Array data with key-value pair to fetch result using knockout js,

In the JS file, we will see a method called getCountryCurrency contains the country list with currency symbol and rate in the array.

We have to print that data using for each in the knockout with given snippet,

We are creating a simple table node of the HTML to display data in some respective manner,

<table>
    <thead>
    <tr>
        <td>Country Name</td>
        <td>Currency</td>
        <td>Rate</td>
    </tr>
    </thead>
    <tbody data-bind="foreach: getCountryCurrency">
        <tr>
            <td data-bind="text: country"></td>
            <td data-bind="text: currency"></td>
            <td data-bind="text: rate"></td>
        </tr>
    </tbody>
</table>

Inside the foreach loop, We are fetching the data by the array key value.
We need to pass the array key to the data-bind syntax of the knockout to fetch data from the complex array.

The result will be displayed in a table tag with the country name, currency symbol, and rate.