lodash:从对象数组中获取对象值

lodash: get an object value from an object array

我有一个如下所示的对象数组。数组中的每个对象都有一个 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'
        }    
    ]
}    

];

这应该有效:

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_.map 的更优雅的解决方案是:

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

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

编辑:_.pluck 因为 v4.x 已弃用,请改用 _.map

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>

所以你知道,普通方法也很短:

var out = arr.reduce(function (p, c) {
  return p.concat(c.instructors.map(function (instructor) {
    return instructor.email;
  }));
}, []);