我有一个如下所示的对象数组。数组中的每个对象都有一个 instructors
字段,它也是一个数组。如何通过 lodash 从这个对象数组中获取所有电子邮件字段?
我需要使用双 _.map 函数吗?我可以在对象中运行一个 foreach,然后在讲师中运行另一个 foreach,但我认为这不是很优雅。我无法全神贯注地从包含其他数组字段的对象数组中获取值。任何帮助将不胜感激。
[
{
'title': 'New Class',
'instructors': [
{
'email': 'someemail@gmail.com'
},
{
'email': 'anotheremail@gmail.com'
}
]
},
{
'title': 'New Class 2',
'instructors': [
{
'email': 'someemail@gmail.com'
},
{
'email': 'anotheremail@gmail.com'
}
]
}
];
最佳答案
Do I need to use a double _.map function?
这是一个解决方案。你相信你在找flatMap
:
var classes = [{
'title': 'New Class',
'instructors': [{
'email': 'someemail@gmail.com'
}, {
'email': 'anotheremail@gmail.com'
}]
}, {
'title': 'New Class 2',
'instructors': [{
'email': 'someemail@gmail.com'
}, {
'email': 'anotheremail@gmail.com'
}]
}];
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>
关于javascript - lodash:从对象数组中获取对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36289103/