KnockoutJS ObservableArray数据分组 [英] KnockoutJS ObservableArray data grouping
问题描述
KnockoutJS是否具有功能,而我可以采取类似的方式:
Does KnockoutJS have a feature whereas I could take something like:
var myArray = ko.observableArray([
{ name: "Jimmy", type: "Friend" },
{ name: "George", type: "Friend" },
{ name: "Zippy", type: "Enemy" }
]);
然后在类型"字段中选择不重复",从而产生如下所示的结果:
Then select distinct on the "type" field, producing a result which looks like this:
(pseudo code)
var distinct = myArray.distinct('type')
// Returns array of two arrays
// distinct[0] is an array of type=Friend
// distinct[1] is an array of type=Enemy
我知道ko.utils.arrayGetDistinctValues,但这并不能完全满足我的要求.我也知道我可以使用ko.utils.arrayGetDistinctValues编写一些循环来获取我想要的东西,我只是想知道是否有其他东西被我忽略的KnockoutJS烘焙了.
I'm aware of ko.utils.arrayGetDistinctValues, but that doesn't exactly do what I want. I'm also aware that I could write a few loops using ko.utils.arrayGetDistinctValues to get what I want, I'm just wondering if there is something else baked into KnockoutJS that I'm overlooking.
推荐答案
KO中没有其他任何东西可以使这一切变得简单.
There is not anything else built into KO to make this any easier.
有很多方法可以使这项工作.例如,您可以将observableArrays扩展为具有distinct
函数.然后,您可以像这样创建observableArray:
There are many ways that you could make this work. For example, you could extend observableArrays to have a distinct
function. Then, you can just create your observableArray like:
this.people = ko.observableArray([
new Person("Jimmy", "Friend"),
new Person("George", "Friend"),
new Person("Zippy", "Enemy")
]).distinct('type');
distinct
函数可能类似于:
ko.observableArray.fn.distinct = function(prop) {
var target = this;
target.index = {};
target.index[prop] = ko.observable({});
ko.computed(function() {
//rebuild index
var propIndex = {};
ko.utils.arrayForEach(target(), function(item) {
var key = ko.utils.unwrapObservable(item[prop]);
if (key) {
propIndex[key] = propIndex[key] || [];
propIndex[key].push(item);
}
});
target.index[prop](propIndex);
});
return target;
};
它支持链接,因此您可以使用不同的属性多次调用distinct
.
It supports chaining so you could call distinct
multiple times with different properties.
此处提供示例: http://jsfiddle.net/rniemeyer/mXVtN/
这确实会在每次更改时重建索引一次,因此,如果您有大量的项目列表,则可能需要探索其他方法(手动订阅)以从索引"数组中添加/删除项目.
This does rebuild the index once on each change, so if you have a huge list of items, then you would want to potentially explore other ways (manual subscriptions) for adding/removing items from the "index" arrays.
这篇关于KnockoutJS ObservableArray数据分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!