开发者

Getting a concrete element from an observableArray

开发者 https://www.devze.com 2023-03-28 06:21 出处:网络
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.

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;
});
0

精彩评论

暂无评论...
验证码 换一张
取 消