I have a question about Knockout foreach binding to a table.
I have an array of columnNames and an array of items.
The items array has a property called ColumnName. How would I use knockout foreach to bind self.items to self.columnNames?
My view model looks like this:
var VM = function () {
var self = this;
self.items = ko.observableArray();
self.columnNames = [ "Name", "Age", "Job"];
};
var vm = new VM();
ko.applyBindings(vm);
vm.items.push([
{
'ColumnName': 'Name',
'Value': 'John'
},
{
'ColumnName': 'Age',
'Value': 25'
}
]);
vm.items.push([
{
'ColumnName': 'Name',
'Value': 'Jane'
},
{
'ColumnName': 'Age',
'Value': 26
},
{
'ColumnName': 'Job',
'Value': 'developer'
}
]);
In my view, I'm guessing I need something like this,
<table>
<thead>
<tr data-bind="foreach: columnNames">
<th> <span data-bind="text: $data"></span>
</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr data-bind="foreach: $parent.columnNames">
<!-- how do I put the Value property here?! -->
</tr>
</tbody>
</table>
I started a jsfiddle here, http://jsfiddle.net/83zcwue7/1/
-update- I'm trying to render something like this:
Name Age Job
John 25
Jane 26 Developer
-- update 2 -- I created an ugly (but working) solution.
http://jsfiddle.net/83zcwue7/7/
I added this method call. It maps the ColumnName as the property name and Value its value, but it feels like I completely missed a simpler solution:
self.fixedItems = ko.observableArray(); //I use this in foreach
self.fixData = function(){
$.each(self.items(), function(i, rows){
var cell = new Object();
$.each(rows, function(j, prop){
cell[prop.ColumnName] = prop.Value;
});
self.fixedItems.push( cell );
});
};
Original data looked like this:
[[{ 'ColumnName': 'Name', 'Value': 'John' }, { 'ColumnName': 'Age', 'Value': 25 }], [{ 'ColumnName': 'Name', 'Value': 'Jane' }, { 'ColumnName': 'Age', 'Value': 22 }, { 'ColumnName': 'Job', 'Value': 'developer' }]]
The result (self.fixedItems) looks like this:
[{ Age: 25 Name: "John" }, { Age: 26, Job: "developer", Name: "Jane" }]
Which 'fixes' the data, so it can be used easily in the foreach. It feels like I missed an elegant solution.
subscribe
check this jsfiddle.net/83zcwue7/8 . good luck – super cool