groupBy
您可以实现为 ember-data DS-ManyArray 对象量身定制的自己的函数并_
使用它进行扩展:
_.emberArrayGroupBy = function(emberArray, val) {
var result = {}, key, value, i, l = emberArray.get('length'),
iterator = _.isFunction(val) ? val : function(obj) { return obj.get(val); };
for (i = 0; i < l; i++) {
value = emberArray.objectAt(i);
key = iterator(value, i);
(result[key] || (result[key] = [])).push(value);
}
return result;
};
现在你可以打电话
var grouped = _.emberArrayGroupBy(activities, function(activity) {
return activity.get('dateLabel');
});
或更简单地说
var grouped = _.emberArrayGroupBy(activities, 'dateLabel');
上面的函数是基于 underscore 的原始groupBy()
实现,看起来非常相似:
_.groupBy = function(obj, val) {
var result = {};
var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
});
return result;
};