Reputation: 597
I have an ugly for loop that I would like to rewrite into lodash. I have an array (allData) which contains an array (grp1) which contains an array (grp2) etc. eg:;
(4) [grp, grp, grp, grp] //the allData Array
0: grp // eg the 0 pointer
grp1: Array(4) // have grp1 Array in it
..
0: grp1 // eg the 0 pointer
grp2: Array(4) // have grp1 Array in it
..
0: grp3 {} // grp3 have now the id
1: grp3
id: (...)
color: (...)
I write an for loop and nested it. It works but in my opionion the code is ugly.
for (let grp1 of allData) {
for (let grp2 of grp1.getIdsForGrp1()) {
for (let grp3 of grp2.getIdsForGrp2()) {
if searchID === grp3.id {
return grp3.id
}
}
}
}
It is possible to rewrite it with lodash?
Upvotes: 0
Views: 234
Reputation: 9985
Bit difficult to give an answer just based on incomplete data, but you might want to do something like
const _ = require(lodash);
_(allData).flattenDeep().find(({id}) => id === searchID);
This assumes that the field 'id' is unique on the requested level (grp3) and is not present in the the first 2 levels (grp1 and grp2).
Hope this helps.
Upvotes: 1