In Knockout JS, is it possible to do a foreach
that increments by 2? Something similar to:
for (var i = 0; i < array.length; i += 2) {
// Do stuff
}
The reason I'd like to do this is because the data that I need to loop through is an array rather than an object. Example:
viewModel = function () {
this.facets = ["Sample", 100, "Sample 2", 200];
}
But the data needs to be displayed like this:
<ul data-bind="foreach: facets"> <!-- Can this foreach be incremented by 2? -->
<li>$data[$index]: $data[$index + 1]</li>
</ul>
Any help would be greatly appreciated.
You could write a custom binding handler for this but I would rather keep the templates free from such ugly details.
I would recommend writing a ko.computed
:
function Model() {
this.data = ko.observableArray(["Sample", 100, "Sample 2", 200])
this.items = ko.computed(function() {
var value = [];
var data = this.data();
for (var i=0; i<data.length; i+=2) {
value.push({ key: data[i], value: data[i+1]);
}
return value;
}, this);
}
var model = new Model();
Now you can iterate over the items
in your template and access key
and value
. Updating the original data
array will automatically rebuild the items
computed observable.
The template code would look like:
<ul data-bind="foreach: items">
<li><span data-bind="text: key"></span>: <span data-bind="text: value"></span></li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With