可观察数组搜索的常规功能 [英] General function for observable array search
本文介绍了可观察数组搜索的常规功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以执行一般功能来搜索可观察数组,如果找到的值将该对象设置为另一个可观察对象. 这个问题与 知道选择:按项目设置所选项目名称不是值
is there a way to do a general function for search an observable array and if the value found then set that object to another observable .? this question relate to Knokout select : Set Selected Item by item name not value
到目前为止,我已经尝试过
so far i have tried
self.getOptionByName = function(instance,opt,name){
console.log(instance()[x]+'."'+opt+'"');
for (var x = 0; x < instance().length; x++) {
console.log(instance()[x].opt);
if (instance()[x].opt == name)
return instance()[x];
}
return null;
}
并称为
self.IssuingcountrySelected(self.popup.getOptionByName(self.issuingCountries,'Country','Japan'))
我的可观察数组是
0:
ObjectCoordinatorRegion: "EU"
Country: "Australia"
CountryId: 14
Id: 1
2:
ObjectCoordinatorRegion: "AU"
Country: "Japan"
CountryId: 16
Id: 2
推荐答案
尝试类似的方法
viewModel:
var ViewModel = function () {
var self = this;
self.IssuingcountrySelected = ko.observable();
self.issuingCountries = ko.observableArray(json);
var getOptionByName = function (instance, opt, name) {
return ko.utils.arrayFirst(instance, function (item) { //returns first matched record
if (item[opt] == name) {
return item[opt];
}
});
}
self.IssuingcountrySelected(getOptionByName(self.issuingCountries(), 'Country', 'Japan'))
//You get the matched object else null
console.log(self.IssuingcountrySelected()) // check console
};
示例工作小提琴 此处
sample working fiddle here
这篇关于可观察数组搜索的常规功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文