1

Is it possible to use data-bind: foreach for more than one array?
For example:

<div data-bind="foreach: arrayone, arraytwo">
   //do stuff
</div>

If it's possible, what is the correct syntax for it ? Or what is the correct way of doing this (besides merging the two arrays) ?

1
  • I'm not sure what this would even do. What would be your expected behavior? Do you want to fully loop through arraytwo for every index of arrayone? Commented Oct 26, 2017 at 17:22

1 Answer 1

1

I don't think there is any official way of doing so, but a workaround would be, to use $index along with foreach on the longer array. Something like this:

var model = function() {
  var self = this;
  
  self.arr1 = ko.observableArray([1,2,3, 5, 6]);
  self.arr2 = ko.observableArray([1,2,3,4]);
  
}

ko.applyBindings(new model());
span {
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<br/>

<div data-bind="foreach: (arr1().length > arr2().length ? arr1 : arr2)">
  Index: 
  <span data-bind="text: $index"></span>,
  
  Array 1: 
  <span data-bind="text: $root.arr1()[$index()]"></span>,
  Array 2: 
  <span data-bind="text: $root.arr2()[$index()]"></span>,
  Longer array: 
  <span data-bind="text: $data"></span>,
  Shorter array: 
  <span data-bind="text: ($root.arr1().length < $root.arr2().length ? $root.arr1()[$index()] : $root.arr2()[$index()])"></span>
  <br/>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.