How to efficiently find a value inside nested objects by underlining each function?

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': [] } } } } 
+4
source share
2 answers

Check out _.some .

 var foundUnit = null; _.some(worldHandler.world, function(zone) { return _.some(zone, function(cellX) { return _.some(cellX, function(cellY) { return _.some(cellY.units, function(unit) { if ( unit.id === id ) {foundUnit = unit; return true; } }); }); }); }); return foundUnit; 

Note that _.some no-ops if the object is null, so there is no need to check it.

+6
source

You can smooth your nested structure into an array of units, and then use _.find on it:

 var zones = _.flatten(_.map(world, _.values)); var cells = _.flatten(_.map(zones, _.values)); var units = _.flatten(_.map(cells, _.values)); var unit = _.find(units, function(u) { return u.id == 7 }); 

If you are concerned about performance, and you are looking up at unit.id , then you should consider creating an index:

 var indexById = {}; _.each(units, function(u) { indexById[u.id] = u; }); 

Then you can do a constant time search: var unit = indexById[7];

+1
source

Source: https://habr.com/ru/post/1485272/


All Articles