2016-11-02 91 views
0

我幾乎沒有使用lodash,我正在嘗試使用它來完成一項簡單的任務。用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。

回答

2

首先,_.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 
    } 
} 
+1

我個人認爲,它讀取如果更換'_.isEmpty()'邏輯更容易:'_.every(component.types,鍵入=> _.includes(validTypes,類型))' – Retsam

+0

我同意,但它可能會降低性能 – Meir

+1

除非另有說明,可讀性勝過性能,imo。 (雖然我不明白爲什麼這個性能比'_.difference'低很多) – Retsam