想要从KoObservableArray中删除重复值。我有以下JS文件。我想将UI中的name列绑定为下拉列表以及删除重复的值。
建议做同样的最好方法。
JS档案
$(function () {
var initialData = [
{ name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
{ name: "Speedy Coyote", sales: 89, price: 190.00 },
{ name: "Furious Lizard", sales: 152, price: 25.00 },
{ name: "Furious Lizard", sales: 213, price: 25.00 },
{ name: "Indifferent Monkey", sales: 1, price: 99.95 },
{ name: "Speedy Coyote", sales: 89, price: 190.00 },
{ name: "Brooding Dragon", sales: 0, price: 6350 },
{ name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
{ name: "Optimistic Snail", sales: 420, price: 1.50 }
];
var PagedGridModel = function (items) {
this.items = ko.observableArray(items);
};
ko.applyBindings(new PagedGridModel(initialData));
});
HTML File
<body>
<nav>
<label for="name">Name</label>
<select id="name" data-bind="options: items, optionsText: 'name', optionsCaption:'All'">
</select>
</nav>
</body>
以上给我下载了重复的名字。
答案 0 :(得分:3)
请参阅下面的示例,了解如何使计算的observable返回数组。我刚刚写下了过滤的逻辑,但它可能不正确或最优,我会留给你改进它。
$(function () {
var initialData = [
{ name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
{ name: "Speedy Coyote", sales: 89, price: 190.00 },
{ name: "Furious Lizard", sales: 152, price: 25.00 },
{ name: "Furious Lizard", sales: 213, price: 25.00 },
{ name: "Indifferent Monkey", sales: 1, price: 99.95 },
{ name: "Speedy Coyote", sales: 89, price: 190.00 },
{ name: "Brooding Dragon", sales: 0, price: 6350 },
{ name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
{ name: "Optimistic Snail", sales: 420, price: 1.50 }
];
var PagedGridModel = function (items) {
var self = this;
self.items = ko.observableArray(items);
self.uniqueItems = ko.computed({
var filteredArray = [];
var i;
$.each(self.items(), function (index, item) {
bool alreadyAdded = false;
for (i in filteredArray) {
if (filteredArray[i].name == item.name) {
alreadyAdded = true;
}
}
if (!alreadyAdded) {
filteredArray.push(item);
}
});
return filteredArray;
});
};
ko.applyBindings(new PagedGridModel(initialData));
});
最后在你的HTML中
<select id="name" data-bind="options: uniqueItems, optionsText: 'name', optionsCaption:'All'">
</select>