【问题标题】:lodash: get an object value from an object arraylodash:从对象数组中获取对象值
【发布时间】:2016-03-29 15:49:33
【问题描述】:

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

];

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    我需要使用双 _.map 函数吗?

    这是一种解决方案。你相信你在找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>

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 不错的解决方案,我们过度使用 lodash 方式经常不考虑原生,兼容直到 IE9
      • @deKajoo,我认为您的意思是“来自 IE9”:)
      【解决方案3】:

      这应该有效:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-27
        • 2015-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多