rsa rsa - 1 year ago 54
jQuery Question

Display dynamic knockout observable array in table

Given an observable array 'sampleList' defined inside the viewModel.

name: abc,
age: 40,
InterestLevel: {
trekking: 50,
hiking : 43

name: def,
age: 34,
InterestLevel: {
cricket: 55,
cycling: 75

How to generate the following table from the above data using KO custom binding or any best possible way.


name age Interest InterestLevel

abc 40 trekking 50
abc 40 hiking 43
def 34 cricket 55
def 34 cycling 75

[please note that the keys inside InterestLevel are dynamic].

Answer Source

First, you'll have to de-normalize your data:

this.TableData = ko.computed(function()
    var data = ko.unwrap(this.sampleList)
    var res = ko.observableArray();

    for (var i in data)
        for (var il in data[i].InterestLevel)
            var ild = data[i].InterestLevel[il];
            res.push({ name: data[i].name, age: data[i].age, Interest: il, InterestLevel: ild });

    return res;
}, this);

Then bind your table to TableData():

             <td>Interest Level</td>

    <tbody data-bind="foreach: TableData()">
             <td data-bind="text: name">Name</td>
             <td data-bind="text: age">Age</td>
             <td data-bind="text: Interest">Interest</td>
             <td data-bind="text: InterestLevel">Interest Level</td>                

See Fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download