2013-10-31 63 views
0
cityArray.indexOf(data.results[index].City) === -1 

如何使用indexOf方法爲每個項目是對象的knockoutObservable數組? cityArray包含一個名爲City的屬性。Knockout Observable Array IndexOf方法

+1

你不能。您可以使用['ko.utils.arrayFirst'](http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html),任何其他數量的現有實用功能,或者自己推出循環。一旦你'var arr = observableArray()'你留下一個正常的數組,然後可以把它當作任何其他的JavaScript數組。 – user2864740

+0

@ user2864740:這應該是答案 – naveen

回答

0
cityArray.indexOf( 
    ko.utils.arrayFirst(ko.utils.unwrapObservable(cityArray), function(cityObj) { 
     return ko.utils.unwrapObservable(cityObj.City) == 'WallaWalla'; 
    } 
) 

的ko.utils.unwrapObservable功能()你的對象,如果它需要它,也不會,如果它不。輕量級...在V2.3中,您只需做ko.unwrap,以防萬一您擔心js中的字母過多。

arrayFirst返回對象,然後indexOf將拉對象的比較,你應該得到你的索引...- 1,如果它不存在...如果沒有匹配arrayFirst,你會得到空。

+1

順便說一下,'ko.unwrap'作爲一個快捷方式實際上是添加在2.3.0 – ebohlman

+0

正確的...上面編輯...感謝指出一個......手指偶爾移動更快比大腦 – beauXjames

1

感謝所有的答案。我試圖使用indexOf方法來查看一個條目是否已經存在於可觀察數組中。相反,我現在使用ko.utils.arrayGetDistinctValues,所以我不再需要使用indexOf方法。但是由於arrayGetDistinctValues不適用於對象數組,因此我首先將值複製到普通數組中,然後使用該函數。

0

這就是我得到了我的arrayIndexOf工作

var viewModel = function() { 
 
    var self = this; 
 

 
    self.suggestions = ko.observableArray([]); 
 
    self.filterText = ko.observable(''); 
 

 
    self.filterText.subscribe(function(newValue) {}); 
 

 
    self.suggestionsFilter = ko.computed(function() { 
 
    
 
    if (self.filterText() === '') { 
 
     return self.suggestions(); 
 
    } else { 
 
     return ko.utils.arrayFilter(self.suggestions(), function(item) { 
 

 
     var filterResults = item.option.toLowerCase().indexOf(self.filterText().toLowerCase()) == 0; 
 
     return filterResults; 
 

 
     }); 
 
    } 
 
    }); 
 
};
<div class="col-md-6 postcode-search" id="js-postcode-search-suggestions"> 
 
    <input id="name-search" class="form-control" type="search" name="postcode" minlength="1" placeholder="Postcode or Address" data-bind="textInput: filterText" /> 
 
    <div class="col-md-12" data-bind="visible: suggestions().length > 1" style="display: none"> 
 
    <ul class="suggestions" data-bind="foreach: suggestionsFilter"> 
 
     <li class="pad-top-bottom"> 
 
     <a href="#"> 
 
      <span class="option" data-bind="html: option"></span> 
 
     </a> 
 
     </li> 
 
    </ul> 
 
    </div> 
 
</div>