Reputation: 487
Is there a way to retrieve an element from inner array in array when using nested lodash find, for example?
I have an array of groups, each element of which has array of children. All children have unique ids (even between groups). I need to get hold of a child with id == value and now I'm doing the following:
Firstly I retrieve needed group:
var group = _(groups).find(g => {return _(g.children).find(c => {return c.id == value})});
Then I get the child:
var child = _(group.children).find(c => {return c.id == value});
Is there a more efficient and elegant way to achieve this?
Upvotes: 1
Views: 407
Reputation: 7416
flat groups by children and find from result
_(groups)
.flatMap('children')
.find({id: value})
.value();
Upvotes: 4
Reputation: 507
There is a another way of doing this using map() and filter()
var filteredArray = [];
_.map(group, function(groupValue) {
var groupChildren = groupValue.children;
var filteredChild = _.filter(groupChildren, function(child) {
return child.id = value
});
if(filteredChild.length != 0) {
filteredArray.push(filteredChild[0]);
return groupValue;
} else {
return groupValue;
}
});
Upvotes: 1