首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带下划线/下划线的复合索引

带下划线/下划线的复合索引
EN

Stack Overflow用户
提问于 2014-12-24 16:56:18
回答 1查看 205关注 0票数 0

在处理数据库中的数据时,我们通常会得到一些内容数组,由于数据库的限制,这些数组可以通过复合索引(唯一地)进行索引。然而,indexBy似乎不适用于复合指数,或者说不是吗?

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

Fiddle here

代码语言:javascript
复制
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现在看起来像这样:

代码语言:javascript
复制
{
    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实际上支持复合索引),或者至少可以改进它?

EN

回答 1

Stack Overflow用户

发布于 2015-01-14 20:55:07

您可以创建递归地对对象进行分组/索引的mixin:

代码语言:javascript
复制
_.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']));

如果您更喜欢与给定索引匹配的对象列表(例如,在具有非唯一路径的情况下):

代码语言:javascript
复制
_.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/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27634153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档