ric*_*van 20 arrays javascript-objects underscore.js
使用Underscore.js,我试图多次对项目列表进行分组,即
然后由SIZE分组为每个SIZE,按类别分组......
http://jsfiddle.net/rickysullivan/WTtXP/1/
理想情况下,我希望有一个函数或扩展,_.groupBy()
以便您可以使用参数对其进行分组.
var multiGroup = ['size', 'category'];
Run Code Online (Sandbox Code Playgroud)
可能只是混合...
_.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);
Run Code Online (Sandbox Code Playgroud)
我的头很痛,但我觉得还有更多需要去的地方......
});
})
return result;
}
});
properties = _.groupByMulti(properties, function(item) {
var testVal = item["size"];
if (parseFloat(testVal)) {
testVal = parseFloat(item["size"])
}
return testVal
}, multiGroup);
Run Code Online (Sandbox Code Playgroud)
Ber*_*rgi 39
一个简单的递归实现:
_.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;
}
});
Run Code Online (Sandbox Code Playgroud)
小智 17
我认为@ Bergi的答案可以通过利用Lo-Dash mapValues
(用于在对象值上映射函数)来简化.它允许我们以嵌套的方式通过多个键对数组中的条目进行分组:
_ = require('lodash');
var _.nest = function (collection, keys) {
if (!keys.length) {
return collection;
}
else {
return _(collection).groupBy(keys[0]).mapValues(function(values) {
return nest(values, keys.slice(1));
}).value();
}
};
Run Code Online (Sandbox Code Playgroud)
我将方法重命名为,nest
因为它最终提供了与D3的嵌套运算符相同的角色.请参阅此要点以获取详细信息以及此示例中演示用法的小提琴.
Pan*_*kaj 15
这个相当简单的黑客怎么样?
console.log(_.groupBy(getProperties(), function(record){
return (record.size+record.category);
}));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27730 次 |
最近记录: |