john
john

Reputation: 834

How to iterate array of arrays using knockout data-bind foreach?

I have an array of arrays that contain objects, and im looking for a way to loop over the inner arrays of the array, something like this:

<div data-bind="foreach: questions">
    <div data-bind="foreach: subArray of questions">
        <span data-bind="text: Title"></span>
        <span data-bind="text: Answer"></span>
    </div>
</div>

How can i access the inner arrays of the questions observableArray so i can loop over the elements?

Fiddle example

thanks in advance for any help!

Upvotes: 1

Views: 1923

Answers (2)

Priyanka Jain
Priyanka Jain

Reputation: 317

I have updated your fiddle . To use inner loop knockout has provided various properties like $data, to use outer loop $parent.

<div class="answers" data-bind="foreach: questions">
    <div data-bind="foreach: $data ">
      <p data-bind="text: Title"></p>
      <p data-bind="text: Answer"></p>  
    </div>  
</div>

Upvotes: 3

Maciej Kwas
Maciej Kwas

Reputation: 6459

It's all in the docs, you just have to access inner arrays with $data: http://knockoutjs.com/documentation/foreach-binding.html

<div class="answers" data-bind="foreach: questions">
  <div data-bind="foreach: $data ">
    <p data-bind="text: Title"></p>
    <p data-bind="text: Answer"></p>  
  </div>
</div>

Upvotes: 2

Related Questions