2016-02-19 20 views
24

私の基準を満たすオブジェクトを返すという単純な機能があります。lodash _.find all matches

コードは次のようになります。

var res = _.find($state.get(), function(i) { 
     var match = i.name.match(re); 
     return match && 
      (!i.restrict || i.restrict($rootScope.user)); 
    }); 

は、どのように私は、この基準が、すべての結果を満たしているすべての結果(ちょうど最初ではない)を見つけることができます。

anzアドバイスありがとうございます。

+2

'_.filter'をお探しですか? – georg

答えて

52

_.filterを使用すると、一致するすべてのアイテムが返されます。用truthyすべての要素述語戻りの配列を返すコレクションの要素上

_.filter

反復し、。述語は、(value、index | key、c​​ollection)の3つの引数で呼び出されます。

6

あなたはそうのようなあなたのすべての要件を渡し、_.filterを使用することができます。

var res = _.filter($state.get(), function(i) { 
     var match = i.name.match(re); 
     return match && 
      (!i.restrict || i.restrict($rootScope.user)); 
    }); 

Link to documentation

3

ES6を使用してlodashせずに、FYI:

Basicの例を(人を取得年齢が30歳未満):

const peopleYoungerThan30 = personArray.filter(person => person.age < 30) 

コードを使用した例:

$state.get().filter(i => { 
    var match = i.name.match(re); 
    return match && 
      (!i.restrict || i.restrict($rootScope.user)); 
}) 
関連する問題