0

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

x给定一个包含具有a和属性的对象的数组b,我想要一个字典字典,其中包含 的所有对象,分别由和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实际上确实支持复合指数),还是至少可以改进?

4

1 回答 1

1

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

于 2015-01-14T12:55:06.613 回答