带有短划线/下划线的复合索引

Compound index with lodash/underscore

本文关键字:下划线 复合 索引      更新时间:2023-09-26

在处理数据库中的数据时,我们经常会得到一些东西的数组,由于数据库的限制,这些数组可以(唯一地)由复合索引进行索引。但是,indexBy似乎不适用于复合指数,还是吗?

给定一个数组x具有属性ab的对象,我想要一个字典字典,其中包含所有x对象,分别按ab索引。例如:

在这里摆弄。

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
            }
        }
    }
}

此小提琴演示了compoundexIndexBy函数。我的工作是徒劳的(因为 Lo-Dash 实际上确实支持复合指数),还是至少可以改进?

您可以创建一个 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/