Q:

Knockout binding, REUSEABLE code for JSON data

I am not able to figure out how to continue for the following data-bind. 
I am having JSON data want to display in form of vertical grid. So I am fetching all the key values in one array(say columnName) and using to display column names. Now I am trying to display the values of JSON data using the array(columnName).
Please check the code, and let me know the solution. 

JavaScript Code:
 var _data = new Array({ firstname: 'Name1', lastname: 'LastName1' }, { firstname: 'Name2', lastname: 'Lastname2' });
var getColumnNames = new Array();
for (key in _data[0]) {
    getColumnNames.push(key);
}

// Here's my data model
var ViewModel = function () {
    this.coulmnNames = ko.observableArray(getColumnNames);
    this.keyValue = ko.observableArray(_data);
};

ko.applyBindings(new ViewModel()); // This makes Knockout get to work

The Actual code is below:
 <div data-bind="foreach: coulmnNames" style="display: inline-block;">
    <div data-bind="text: $data"></div>
</div>

<div data-bind="foreach: keyValue" style="display: inline-block;">
    <div style="display: inline-block;">
        <div data-bind="text: firstname"></div>
        <div data-bind="text: lastname"></div>
    </div>
</div>

Want to code like this:
 <div data-bind="foreach: coulmnNames" style="display: inline-block;">
    <div data-bind="text: $data"></div>
</div>

<div data-bind="foreach: keyValue" style="display: inline-block;">
    <div style="display: inline-block;">
        <div data-bind="foreach: $parent.coulmnNames">
            <div data-bind="text: ???????"></div>
        </div>
    </div>
</div>

I am just trying to write a reuse-able code, just have to vary the JSON data.
Thanks in advance.

A:

You are almost there:

you need to reference the "current data" from the outer loop in the inner loop with $parent
you can use the indexer syntax to dynamically access a property in your inner loop with writing $parent[$data] where $data is the actual column name

So your binding should look like:
<div data-bind="foreach: keyValue" style="display: inline-block;">
    <div style="display: inline-block;">
        <div data-bind="foreach: $parent.coulmnNames">
            <div data-bind="text: $parent[$data]"></div>
        </div>
    </div>
</div>

Demo JSFiddle.
You can read more about the $parent and $data binding context properties in the documentation.

