In my game, I need find a certain monster that is contained in an "units" array. This array is inside a spatial cell structure inside a world object. How can I find this unit without writing ugly code?
var foundUnit = null;
_.each(worldHandler.world, function(zone) {
if ( foundUnit ) return;
_.each(zone, function(cellX) {
if ( foundUnit ) return;
_.each(cellX, function(cellY) {
if ( foundUnit ) return;
if ( !_.isUndefined(cellY.units) ) {
_.each(cellY.units, function(unit) {
if ( foundUnit ) return;
if ( unit.id === id ) foundUnit = unit;
});
}
});
});
});
return foundUnit;
The trouble here is that I can't use return when I found the right value. Return inside the _.each() will just continue that current loop. Is there a better/cleaner way to find a certain value inside a nested object?
Example data:
{ // World
'1': { // Zone
'-1': { // Cell X
'-1': { // Cell Y
'units': []
},
'0': {
'units': [{id:5}]
},
'1': {
'units': []
}
}
} {
'0': {
'-1': {
'units': []
},
'0': {
'units': []
},
'1': {
'units': []
}
}
} {
'1': {
'-1': {
'units': []
},
'0': {
'units': []
},
'1': {
'units': []
}
}
}
}
fororfor...inloops instead ;)