可观察数组搜索的常规函数

时间:2015-06-15 11:01:35

标签: knockout.js

有没有办法为搜索可观察数组做一般函数,如果找到值,则将该对象设置为另一个observable。 这个问题涉及到 Knokout select : Set Selected Item by item name not value

到目前为止我已经尝试了

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

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

<强>视图模型:

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 
};

示例工作小提琴 here

答案 1 :(得分:0)

我有另一种方式,让我知道以下代码是否是标准方式

self.findOptionByName = function(instance,opt,name){            
            for (var x = 0; x < instance().length; x++) {
                var curObj = instance()[x];
                if ( curObj.hasOwnProperty(opt) && curObj[opt] === name){
                    return instance()[x];
                }
           }
           return null;
        } 

然后打电话给

 self.IssuingcountrySelected(self.findOptionByName(self.issuingCountries,'Country',country));