在处理数据库中的数据时,我们通常会得到一些内容数组,由于数据库的限制,这些数组可以通过复合索引(唯一地)进行索引。然而,indexBy似乎不适用于复合指数,或者说不是吗?
给定一个数组x,其中的对象具有属性a和b,我希望有一个字典字典,其中包含x的所有对象,分别由a和b索引。例如:
Fiddle here。
var x = [
{
a: 1,
b: 11,
c: 101
},
{
a: 2,
b: 11,
c: 101
},
{
a: 1,
b: 11,
c: 102
},
{
a: 1,
b: 14,
c: 102
},
];
// index x by a, then by b, then by c
var byABC = _.compoundIndexBy(x, ['a', 'b', 'c']);
// there are two items in `x` with a = 1 and b = 11
console.assert(_.size(byABC[1][11]) == 2, 'Something went wrong...');
// display result
console.log(byABC);byABC现在看起来像这样:
{
1: {
11: {
101: {
a: 1,
b: 11,
c: 101
},
102: {
a: 1,
b: 11,
c: 102
}
},
14: {
102: {
a: 1,
b: 14,
c: 102
}
},
}
2: {
11:{
101: {
a: 2,
b: 11,
c: 101
}
}
}
}This Fiddle演示了compoundexIndexBy函数。我的工作是徒劳的吗(因为Lo-Dash实际上支持复合索引),或者至少可以改进它?
发布于 2015-01-14 20:55:07
您可以创建递归地对对象进行分组/索引的mixin:
_.mixin({
compoundIndexBy: function(lst, iteratees, context) {
if (iteratees.length === 1)
return _.indexBy(lst, iteratees[0], context);
var grouped = _.groupBy(lst, iteratees[0], context);
_.each(grouped, function(sublst, k) {
grouped[k] = _.compoundIndexBy(sublst, _.rest(iteratees), context);
});
return grouped;
}
});
console.dir(_.compoundIndexBy(x, ['a', 'b', 'c']));如果您更喜欢与给定索引匹配的对象列表(例如,在具有非唯一路径的情况下):
_.mixin({
compoundGroupBy: function(lst, iteratees, context) {
var grouped = _.groupBy(lst, iteratees[0], context);
if (iteratees.length === 1)
return grouped;
_.each(grouped, function(sublst, k) {
grouped[k] = _.compoundGroupBy(sublst, _.rest(iteratees), context);
});
return grouped;
}
});
console.dir(_.compoundGroupBy(x, ['a', 'b', 'c']));和一个演示http://jsfiddle.net/nikoshr/8w4n31vb/
https://stackoverflow.com/questions/27634153
复制相似问题