Search code examples
javascriptscreeps

Iterating through a filtered list returns undefined


Can someone explain why harvesters[i] would return undefined in this case? I've used similar code before with no issues. This is for the game Screeps.

  var harvesters=_(Game.creeps).filter( { memory: { role: 'harvester' } } );

  for(var i in harvesters)
  {
    //console.log(harvesters[i]); //this is the debug code I mention below
    harvesters[i].memory.sourceid=0;
  }
}

After some testing (thanks to the comments) I found that harvesters[i] did not return the harvester object I expected.... each harvester is apparently an instance of

function wrapperValue() {
      return baseWrapperValue(this.__wrapped__, this.__actions__);
    }

when I try outputting it to console. Why isnt this a creep object?


Solution

  • You're currently using lodash's chained sequence functionality, in order to extract the unwrapped value you'll need to call .value().

    Your code will have to look somewhat like this:

    const harvesters = _(Game.creeps).filter(
      {
        memory: {
          role: 'harvester'
        }
      }
    ).value();
    

    Alternatively you can use _.filter directly:

    const harvesters = _.filter(Game.creeps, {
      memory: {
        role: 'harvester'
      }
    });