Reputation: 883
cityArray.indexOf(data.results[index].City) === -1
How can I use indexOf method for a knockoutObservable array where each item is an object ? cityArray contains objects with a property called City.
Upvotes: 0
Views: 6993
Reputation: 703
This is how i got my arrayIndexOf to work
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>
Upvotes: 0
Reputation: 8418
cityArray.indexOf(
ko.utils.arrayFirst(ko.utils.unwrapObservable(cityArray), function(cityObj) {
return ko.utils.unwrapObservable(cityObj.City) == 'WallaWalla';
}
)
The ko.utils.unwrapObservable function will () your object if it needs it and won't if it doesn't. Lightweight...in V2.3 you can just do ko.unwrap just in case you have a fear of too many letters in your js.
The arrayFirst returns the object then the indexOf will pull the comparison of the object and you should get your index...-1 if it doesn't exist...if there are no matches with arrayFirst, you'll get null.
Upvotes: 0
Reputation: 883
Thanks all for the answers. I was trying to use indexOf method to see if an entry already exists in an observable array. Instead I am now using ko.utils.arrayGetDistinctValues so I no longer have to use indexOf method. But since arrayGetDistinctValues does not work on array of objects, I first copied the values in to a normal array and then used the function on it.
Upvotes: 1