This seems easy but after two hours my head hurts.
I have a categoryIndex (from a select) and I want to get the category from an observableArray who have that Id.
How I do that? I tried with indexOf (but Im not sure how it works and I looked the doc of course), I tried linq.js but the Where is hard to use or Im stupid (I don't know how to get the Id from a category and compare it).
My observableArray is this:
categories[category { Id=2, Name="Pink", ...}, category { Id=1, Name="Green", ...}]
So, I just need one way to get the "Pink" category if my Index is 2.
Thank you.
EDIT:
viewModel.addNote = function() {
var selectedCategoryIndex = $("#Categories").val();
var selectedCategory = ko.utils.arrayFirst(this.categories(), function(item) {
return item.Id === selectedCategoryIndex;
});
}.bind(viewModel);
I usually use a KO utility function ko.utils.arrayFirst
to do this type of thing. It just loops through an array and returns the first item that matches the predicate passed to it.
You would use it like this:
selectedId = 2;
var category = ko.utils.arrayFirst(categories(), function(category) {
return category.Id === selectedId;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With