I tryed to get indexOf
object
which is in observable array ( Knockout
). What I tryed to do show this simple example:
var arrayObjectIndexOf = function arrayObjectIndexOf(myArray, searchTerm, property) {
for (var i = 0, len = myArray.length; i < len; i++) {
if (myArray[i][property] === searchTerm) return i;
}
return -1;
};
var sampleArray = [{ItemID: "2", ItemName: "name1"}, {ItemID: "3", ItemName: "name2"}]
sampleArray: ko.observableArray();
arrayObjectIndexOf(sampleArray(), "2", "ItemID"); // it's always returns me -1 but should in this sample return index equal to 0
myArray[i][property]
it's returns function not really value to compare to.
The Question is how can I make it work as it should?
If something isn't clear here please ask.
You need to use the ko.unwrap
(or ko.utils.unwrapObservable
if you are using an older version of KO) to make sure that you are always working with the underlying values and not with the observables:
var arrayObjectIndexOf = function arrayObjectIndexOf(myArray, searchTerm, property) {
var unwrappedArray = ko.unwrap(myArray);
for (var i = 0, len = unwrappedArray.length; i < len; i++) {
if (ko.unwrap(unwrappedArray[i][property]) === searchTerm) return i;
}
return -1;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.