Underscore.js groupBy 多个值 [英] Underscore.js groupBy multiple values
本文介绍了Underscore.js groupBy 多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 Underscore.js,我试图多次对项目列表进行分组,即
Using Underscore.js, I'm trying to group a list of items multiple times, ie
按 SIZE 分组,然后对于每个 SIZE,按 CATEGORY 分组...
Group by SIZE then for each SIZE, group by CATEGORY...
http://jsfiddle.net/rickysullivan/WTtXP/1/
理想情况下,我想要一个函数或扩展 _.groupBy()
以便您可以将数组与要分组的参数一起扔给它.
Ideally, I'd like to have a function or extend _.groupBy()
so that you can throw an array at it with the paramaters to group by.
var multiGroup = ['size', 'category'];
可能只是做一个 mixin...
Probably could just make a mixin...
_.mixin({
groupByMulti: function(obj, val, arr) {
var result = {};
var iterator = typeof val == 'function' ? val : function(obj) {
return obj[val];
};
_.each(arr, function(arrvalue, arrIndex) {
_.each(obj, function(value, objIndex) {
var key = iterator(value, objIndex);
var arrresults = obj[objIndex][arrvalue];
if (_.has(value, arrvalue))
(result[arrIndex] || (result[arrIndex] = [])).push(value);
我的头很痛,但我认为这里需要更多的推动......
My head hurts, but I think some more pushing needs to go here...
});
})
return result;
}
});
properties = _.groupByMulti(properties, function(item) {
var testVal = item["size"];
if (parseFloat(testVal)) {
testVal = parseFloat(item["size"])
}
return testVal
}, multiGroup);
推荐答案
一个简单的递归实现:
_.mixin({
/*
* @mixin
*
* Splits a collection into sets, grouped by the result of running each value
* through iteratee. If iteratee is a string instead of a function, groups by
* the property named by iteratee on each of the values.
*
* @param {array|object} list - The collection to iterate over.
* @param {(string|function)[]} values - The iteratees to transform keys.
* @param {object=} context - The values are bound to the context object.
*
* @returns {Object} - Returns the composed aggregate object.
*/
groupByMulti: function(list, values, context) {
if (!values.length) {
return list;
}
var byFirst = _.groupBy(list, values[0], context),
rest = values.slice(1);
for (var prop in byFirst) {
byFirst[prop] = _.groupByMulti(byFirst[prop], rest, context);
}
return byFirst;
}
});
这篇关于Underscore.js groupBy 多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文