Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a concrete element from an observableArray

Tags:

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);
like image 695
Jesus Rodriguez Avatar asked Aug 12 '11 17:08

Jesus Rodriguez


1 Answers

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;
});
like image 146
RP Niemeyer Avatar answered Oct 13 '22 10:10

RP Niemeyer