来自observableArray对象属性的唯一项

Joe*_*Joe 8 filtering ko.observablearray knockout.js

我正在尝试从knockout.js observableArray对象中提取唯一属性,以填充下拉菜单.作为淘汰赛的新手,我真的很挣扎!

我想迭代一个联系人列表,并使用observableArray中每个person对象的唯一值填充一个drop菜单.所以在我下面的代码示例中,我希望在我的下拉菜单中填入一个人类'类型'列表 - 家人,朋友等.

在Google上看,我发现了一个类似的功能,但是它没有返回任何值,即使我在console.log结果中也是如此?

//dummy data more rows in actual code...

var people = [
    { name: "Contact 1", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "family" },
    { name: "Contact 2", address: "1, a street, a town, a city, AB12 3CD", tel: "0123456789", email: "anemail@me.com", type: "friend" }
];


function ContactsViewModel(people) {

    var self = this;
    self.contacts = ko.observableArray(people);

    self.uniqueSelect = ko.dependentObservable(function() {
        return( ko.utils.arrayGetDistinctValues(self.contacts().type).sort());
    }, self);
};

ko.applyBindings(new ContactsViewModel(people));
Run Code Online (Sandbox Code Playgroud)

和HTML模板

<p>Show me: <select data-bind="options: ContactsViewModel.uniqueSelect"></select></p>
Run Code Online (Sandbox Code Playgroud)

任何帮助赞赏,作为一个菜鸟我迷路了!谢谢

Art*_*kov 13

你不能使用这样的结构self.contacts().type.您应首先获取类型数组,然后调用Distinct函数:

self.uniqueSelect = ko.dependentObservable(function() {
    var types = ko.utils.arrayMap(self.contacts(), function(item){ return item.type})
    return ko.utils.arrayGetDistinctValues(types).sort();
});
Run Code Online (Sandbox Code Playgroud)

这是工作小提琴:http://jsfiddle.net/VxT5Y/