【问题标题】:Deep array selection with lodash使用 lodash 进行深度数组选择
【发布时间】:2016-11-02 18:00:33
【问题描述】:

我几乎没有使用过 lodash,现在我正在尝试将它用于一个简单的任务。

我有一个可行的解决方案,但它看起来很复杂,我想知道是否有使用库实用程序的简单快捷方式。

items 是一个对象数组,如下所示:

{
    id: ‘string’,
    val_1: ‘string’,
    val_2: ‘string’,
    components: array of: {
        val_3: ‘string’,
        val_4: ‘string’,
        types: array of strings
    }
}

我想选择一个其组件数组包含有效类型的对象。 有效类型由我在大约 10 个字符串的数组中定义。这是我的解决方案:

var validTypes = [‘type1’,’type3’,’type5’];
var desired = _.find(items, (item) => {
    var allowed = true;
    _.forEach(item.components, (component) => {
        // Remove valid types. What's left should be empty.
        _.pullAll(component.types, validTypes);
        allowed = allowed && _.isEmpty(component.types);
    })
    return allowed;
});

如上所述,我想知道如何改进,我觉得我没有正确使用 lodash。

【问题讨论】:

    标签: javascript underscore.js lodash


    【解决方案1】:

    首先,_.pullAll 改变你的对象并且不应该被使用。

    您可以改用_.every_.some,一旦发现不可接受的值,这将停止循环。

    var validTypes = [‘type1’,’type3’,’type5’];
    var desired = _.find(items, (item) => {
        return _.every(item.components, (component) => { // all components must be valid
            return _.isEmpty(_.difference(component.types, validTypes)); // there shouldn't be any types that are not in the valid
        }
    }
    

    【讨论】:

    • 就个人而言,我认为如果将_.isEmpty() 逻辑替换为:_.every(component.types, type => _.includes(validTypes, type))
    • 除非另有说明,否则可读性胜过性能,imo。 (虽然我不明白为什么它的性能会低于_.difference
    • 特朗普本周是一个有趣的词汇选择?
    • 谢谢你们,不知何故我错过了_.every()。顺便提一下@Retsam 的建议。
    猜你喜欢
    • 1970-01-01
    • 2017-01-07
    • 2021-11-26
    • 1970-01-01
    • 2016-09-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多