Search code examples
knockout.jsknockout-2.0

knockout, whats the best way to find a value in observableArray


I have an observableArray, I have a name "Zippy", I need to check if it is in the array. if this name exists, I need to get its type. how should I do that?

// This observable array initially contains three objects
var anotherObservableArray = ko.observableArray([
    { name: "Bungle", type: "Bear" },
    { name: "George", type: "Hippo" },
    { name: "Zippy", type: "Unknown" }
]);

Solution

  • Try this, you can use ko.utils.arrayFirst function for checking an element with your custom logic..

    var name = "Zippy";
    var match = ko.utils.arrayFirst(anotherObservableArray(), function(item) {
        return item.name == name;
    });
    
    var type;
    
    if(match)
       type = match.type