使用Underscore.js,我试图多次对项目列表进行分组,即
然后按SIZE分组,然后针对每个SIZE,按CATEGORY分组...
http://jsfiddle.net/rickysullivan/WTtXP/1/
理想情况下,我想拥有一个函数或扩展 _.groupBy()
,以便您可以使用参数对数组进行分组。
var multiGroup = ['size', 'category'];
可能只是混搭...
_.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);
我的头很痛,但我认为还需要更多 push ...
});
})
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;
}
});
Demo in your jsfiddle
关于arrays - Underscore.js组通过多个值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10022156/