When working with data from database, we often get arrays of stuff that, due to database constraints, can be (uniquely) indexed by compound indices. However, indexBy
does not seem to work for compound indices, or does it?
Given an array x
with objects that have properties a
and b
, I want to have a dictionary of dictionaries that contain all objects of x
, indexed by a
and b
, respectively. For example:
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
now looks like this:
{
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 demonstrates the compoundexIndexBy
function. Is my work in vain (because Lo-Dash actually does support compound indices), or can it at least be improved?