Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" }
]);
like image 930
qinking126 Avatar asked Oct 31 '12 14:10

qinking126


People also ask

What is Ko computed in knockout JS?

ko. computed( evaluator [, targetObject, options] ) — This form supports the most common case of creating a computed observable. evaluator — A function that is used to evaluate the computed observable's current value. targetObject — If given, defines the value of this whenever KO invokes your callback functions.

What is Ko observableArray?

An observableArray just tracks which objects it holds, and notifies listeners when objects are added or removed.

What does Ko unwrap do?

unwrapObservable(item) Looking at the code, that call basically checks to see if item is an observable. If it is, return the value(), if it's not, just return the value.


1 Answers

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
like image 102
Yograj Gupta Avatar answered Nov 08 '22 13:11

Yograj Gupta