2016-03-29 18 views
1

私は以下のようなオブジェクト配列を持っています。配列内の各オブジェクトには配列でもあるinstructorsフィールドがあります。このオブジェクト配列からすべての電子メールフィールドをlodash経由で取得するにはどうすればよいですか?lodash:オブジェクト配列からオブジェクト値を取得する

ダブル_.map関数を使用する必要がありますか?私はオブジェクトでforeachを実行することができますし、インストラクターで別のforeachを実行することができますが、私はそれが非常にエレガントだとは思わない。私は、他の配列フィールドを含むオブジェクト配列から値を取得することに頭を落とすことはできません。どんな助けでも大歓迎です。

[ 
{ 
    'title': 'New Class', 
    'instructors': [ 
     { 
      'email': '[email protected]' 
     }, 
     { 
      'email': '[email protected]' 
     }  
    ] 
}, 
{ 
    'title': 'New Class 2', 
    'instructors': [ 
     { 
      'email': '[email protected]' 
     }, 
     { 
      'email': '[email protected]' 
     }  
    ] 
}  

];

答えて

3

ダブル_.map関数を使用する必要がありますか?

これは1つの解決策です。 、バニラ方法があまりにもかなり短いです

var classes = [{ 
 
    'title': 'New Class', 
 
    'instructors': [{ 
 
    'email': '[email protected]' 
 
    }, { 
 
    'email': '[email protected]' 
 
    }] 
 
}, { 
 
    'title': 'New Class 2', 
 
    'instructors': [{ 
 
    'email': '[email protected]' 
 
    }, { 
 
    'email': '[email protected]' 
 
    }] 
 
}]; 
 

 
var emails = _.flatMap(classes, function(cls) { 
 
    return _.map(cls.instructors, 'email'); 
 
}); 
 

 
document.querySelector('#out').innerHTML = JSON.stringify(emails, null, 4);
<script src="https://cdn.jsdelivr.net/lodash/4.6.1/lodash.min.js"></script> 
 
<pre id="out"></pre>

0

これは動作するはずです:

_.reduce_.mapを使用して、よりエレガントな解決策は以下のようになり
var allEmails = []; 

_.each(myArray, function(obj) { 
    _.each(obj.instructors, function(instructor) { 
    allEmails.push(instructor.email); 
    }, this); 
}, this); 

return allEmails; 

https://jsfiddle.net/k4uahqkk/1/

_.reduce(myArray, function(result, value, key) { 
    return result.concat(_.map(value.instructors, 'email')); 
}, []); 

https://jsfiddle.net/z1tg4tro/4/

編集:_.pluck v4.xは廃止予定ですので、代わりに_.mapを使用してください。

+0

ここに... –

+0

私は申し訳ありません編集 – deKajoo

3

は、あなたが知っている:あなたはflatMapを探していると信じて

var out = arr.reduce(function (p, c) { 
    return p.concat(c.instructors.map(function (instructor) { 
    return instructor.email; 
    })); 
}, []); 
あなたのフィドルのコードは、あなたが持っているコードとは異なり
+0

良い解決策、私たちは頻繁にネイティブ、思考せずにロダッシュの方法を過剰に使用する** IE9 ** – deKajoo

+0

@deKajoo、私は思いますあなたは "IE9から"を意味する:) – Andy

関連する問題