Get index of item in a loop to be used in if statement to get value in another object

Tags: ,



I’m trying to use the index of the current item in a loop to grab a value from a parent object, I’m only able to get the data if I put the number directly in. However, I need to use the index instead.

So Parent object contains Library, Books and Book prices

<!-- ko foreach: value().Library -->
      <ul>
      <li>
          <div>
               <h3 data-bind="text: Name + ' - ' +  Description"></h3>
          </div>
 <!-- ko if: $parent.value().BookPrices.length > 0  -->
          <div>
               <span data-bind="text: $parent.value().BookPrices[1].Dollars"></span>
          </div>
 <!-- /ko -->
    </li>
    </ul>
 <!-- /ko -->

Any ideas/suggestions how I can use the index or even the ID attribute of the current item in the loop to get the value Dollars using [ ] would be appreciated.

Answer

Something like this?

function ViewModel() {
  var self = this;
  self.value = ko.observable({
    Library: [{
        Id: 1,
        Name: 'Test 1',
        Description: 'Test 1 Description'
      },
      {
        Id: 2,
        Name: 'Test 2',
        Description: 'Test 2 Description'
      },
      {
        Id: 3,
        Name: 'Test 3',
        Description: 'Test 3 Description'
      }
    ],
    BookPrices: [{
      Id: 1,
      Dollars: 5.99
    }, {
      Id: 2,
      Dollars: 9.99
    }, {
      Id: 3,
      Dollars: 15.99
    }]
  })
  
  self.getBookPrice = function(item){
    var result = self.value().BookPrices.filter(x=>x.Id == item.Id);
    return result.length === 0 ? 0.00 : result[0].Dollars;
  
  }

}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko foreach: value().Library -->
<ul>
  <li>
    <div>
      <h3 data-bind="text: Name + ' - ' +  Description"></h3>
    </div>
    <!-- ko if: $parent.value().BookPrices.length > 0  -->
    <div>
      <span data-bind="text: $parent.getBookPrice($data)"></span>
    </div>
    <!-- /ko -->
  </li>
</ul>
<!-- /ko -->


Source: stackoverflow