title: Going through a JSON document array in Javascript & JQuery with KnockoutJS
body: <p>Right now I have the following JSON document:</p>
  
  <pre><code>[
     {
        "price":"1.0",
        "shares":13
     },
     {
        "price":"2.0",
        "shares":5
     },
     {
        "price":"3.0",
        "shares":24
     }
  ]
  </code></pre>
  
  <p>If someone wants 20 shares, I want to return the lowest price possible for 20 shares. In this case its:</p>
  
  <p>13 shares at $1 ($13)</p>
  
  <p>5 shares at $2 ($10)</p>
  
  <p>2 shares at $3 ($6)</p>
  
  <p>the total cost is $29</p>
  
  <p>The specific knockout code I have to do this gets the 20 shares from a previously defined (and working) this.wantedShares() binding.</p>
  
  <p>code:</p>
  
  <pre><code>    this.totalCost = ko.computed(function(){                
              var wantedShares = this.wantedShares();
              var shareCounter = 0.00;
              var counter = 0;
              var totalPrice = 0.00;
  
              $.getJSON("sell.json", function(json){  
                  $.each(json, function() {
                      if(shareCounter &lt;= wantedShares){
                      shareCounter = shareCounter + json[counter].shares;
                      totalPrice = totalPrice + (json[counter].price * json[counter].shares);
                      counter++;
                      }
                  });
              });
              return totalPrice;
      }, this);
  </code></pre>
  
  <p>This code doesn't work, whatever is happening, its not updating totalPrice at all - it remains at 0. Any ideas?</p>