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

qinking126 picture qinking126 · Oct 31, 2012 · Viewed 13.2k times · Source

I have an observableArray, I have a name "Zippy", I need to check if it is in hte 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" }
]);

Answer

Yograj Gupta picture Yograj Gupta · Oct 31, 2012

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