How to put data into nested array and bind it to html in knockout.js?

by muriel.schmidt , in category: Javascript , 2 days ago

How to put data into nested array and bind it to html in knockout.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 21 hours ago

@muriel.schmidt 

In order to put data into a nested array and bind it to HTML using Knockout.js, you can follow these steps:

  1. Define your data structure with nested arrays and objects:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
var viewModel = {
    parentArray: [
        {
            name: "Parent 1",
            childArray: [
                { name: "Child 1", value: 1 },
                { name: "Child 2", value: 2 }
            ]
        },
        {
            name: "Parent 2",
            childArray: [
                { name: "Child 3", value: 3 },
                { name: "Child 4", value: 4 }
            ]
        }
    ]
};


  1. Create a Knockout.js view model using the ko.observableArray and ko.observable functions:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
var viewModel = {
    parentArray: ko.observableArray([
        {
            name: "Parent 1",
            childArray: ko.observableArray([
                { name: "Child 1", value: 1 },
                { name: "Child 2", value: 2 }
            ])
        },
        {
            name: "Parent 2",
            childArray: ko.observableArray([
                { name: "Child 3", value: 3 },
                { name: "Child 4", value: 4 }
            ])
        }
    ])
};


  1. Bind the data to your HTML using Knockout.js bindings:
1
2
3
4
5
6
7
8
<div data-bind="foreach: parentArray">
    <h3 data-bind="text: name"></h3>
    <ul data-bind="foreach: childArray">
        <li>
            <span data-bind="text: name"></span> - <span data-bind="text: value"></span>
        </li>
    </ul>
</div>


  1. Apply the bindings to the HTML element:
1
ko.applyBindings(viewModel);


With these steps, you can put data into nested arrays and objects, bind it to HTML using Knockout.js, and display the nested array data in your web application.