In my game I need to find a specific monster, which is contained in the "units" array. This array is located inside the spatial structure of the cell inside the object of the world. How can I find this machine 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 problem is that I cannot use return when I found the correct value. The return inside _.each () will continue this current loop. Is there a better / cleaner way to find a specific value inside a nested object?
Sample 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': [] } } } }
source share