Lodash's documentation for map()
contains an example like this:
var users = [{'user': 'barney'}, {'user': 'fred'}];
_.map(users, 'user'); // => ['barney', 'fred']
I have data similar to that, but nested. Theirs is an array of objects, but I have an array of objects, each of which contains an array of objects, too. Expanding on the Lodash example, my data is like this:
var users = [
{'mapping': [{'user': 'barney'}, {'user': 'fred'}]},
{'mapping': [{'user': 'sherlock'}, {'user': 'watson'}]},
];
I'd like to get back all four of those names. (An array of arrays is acceptable.)
I tried a number of ways to do this. You can see my attempts at: https://runkit.com/lsloan0000/lodash-map-nested
Eventually, I found this solution:
// I didn't think it would take this much code
_.map(users, function (value, key, collection) {
return _.map(value.mapping, 'user');
});
I thought Lodash has so many features that I wouldn't need to use a callback function.
Is there a simpler way to accomplish this?
I know I can probably skip the key
and collection
arguments. Eventually, I plan to have this code return the objects whose mapping
contains two specific names. (All objects with mappings for "fred" and "barney" together.) So I've left those arguments there, because I think I will need them for that purpose.