我有一个像下面这样的对象数组。数组中的每个对象都有一个instructors
字段,该字段也是一个数组。如何通过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]'
}
]
}
];
我是否需要使用双_.map函数?
那是一个解决方案。您相信您正在寻找flatMap
:
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句