How to use indexOf in KnockoutJS

后端 未结 1 1092
灰色年华
灰色年华 2021-02-03 19:49

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

相关标签:
1条回答
  • 2021-02-03 20:41

    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
    
    0 讨论(0)
提交回复
热议问题