Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use indexOf in KnockoutJS

Tags:

knockout.js

All the examples I see of using the IndexOf() method in KnockoutJS are of basic string types. What I want to know is how to return the index of a array that is an object, based on one of the object variables.

like image 803
user656822 Avatar asked Aug 03 '11 12:08

user656822


People also ask

What is ko observableArray?

Behind the scenes, an observableArray is actually an observable whose value is an array (plus, observableArray adds some additional features described below). So, you can get the underlying JavaScript array by invoking the observableArray as a function with no parameters, just like any other observable.

What is an observable array?

ObservableArray is an array that allows listeners to track changes when they occur.


1 Answers

An observableArray exposes a method called indexOf, which is a wrapper to ko.utils.arrayIndexOf that simply loops through the array looking for the item that you pass to it.

So, if you have the item you can do:

var viewModel = {    items: ko.observableArray([{id: 1, name: "one"}, {id:2, name: "two"}]) };  var item = viewModel.items()[1];  console.log(viewModel.items.indexOf(item)); //equals 1 

If you just have something like a key, then KO does have a utility function called ko.utils.arrayFirst that just loops through the array trying to match the condition that you pass to it. However, it returns the item and not the index of it. It would be slightly inefficient to get the object and then call indexOf on it, as you would make two passes through the array.

You could just write a loop yourself looking for the right item or write a generic function based on ko.utils.arrayFirst that would look like:

function arrayFirstIndexOf(array, predicate, predicateOwner) {     for (var i = 0, j = array.length; i < j; i++) {         if (predicate.call(predicateOwner, array[i])) {             return i;         }     }     return -1; } 

Now, you can pass an array, a condition, and you will be returned the index of the first item that matches.

var viewModel = {     items: ko.observableArray([{         id: 1,         name: "one"},     {         id: 2,         name: "two"}]) };  var id = 2;  console.log(arrayFirstIndexOf(viewModel.items(), function(item) {    return item.id === id;     })); //returns 1 
like image 127
RP Niemeyer Avatar answered Sep 16 '22 14:09

RP Niemeyer