1

I have an object array like the following. Each object in the array has an instructors field which is also an array. How can I get all email fields from this object array via lodash?

Do I need to use a double _.map function? I can run a foreach in the object and then another foreach in the instructors but I don't think that's very elegant. I can't wrap my head around getting values from object arrays that contain other array fields. Any help would be greatly appreciated.

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

];

3 Answers 3

4

Do I need to use a double _.map function?

That's one solution. You believe you are looking for 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>

Sign up to request clarification or add additional context in comments.

Comments

3

So you know, the vanilla method is quite short too:

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

2 Comments

Nice solution, we over-use lodash way to often without thinking native, compatible until IE9
@deKajoo, I think you meant "from IE9" :)
0

This should work :

var allEmails = [];

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

return allEmails;

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

A more elegant solution using _.reduce and _.map would be :

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

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

edit: _.pluck since v4.x is deprecated, use _.map instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.