Lodash: _.forEach() incorrectly iterates over objects with `length` property

Created on 29 Apr 2015  路  3Comments  路  Source: lodash/lodash

I came across an unexpected behavior in _.forEach(). Take the following code:

var data = { length: 3 };
_.forEach(data, function(value, key) {
  console.log(value, key);
});

This outputs:

undefined 0
undefined 1
undefined 2

While I would expect it to output:

3 "length"

For example, when I do:

var data = { foo: 3 };
_.forEach(data, function(value, key) {
  console.log(value, key);
});

I get:

3 "foo"

It appears the logic for determining if { length: 3 } is an array or an object is incorrect and is causing us to iterate over an array of [undefined, undefined, undefined]. I see the incorrect assumption pretty clearly in the isArrayLike() method of the Underscore build, but am not sure exactly where this code lives in the actual lodash source. I assume _.forEach() is not the only method susceptible to this issue.

invalid

Most helpful comment

Hi @jwngr! This is by design. _.each is a "Collection" method and as such prioritizes array-like objects over object iteration. If you're wanting just object iteration try _.forOwn or _.forIn.

All 3 comments

Hi @jwngr! This is by design. _.each is a "Collection" method and as such prioritizes array-like objects over object iteration. If you're wanting just object iteration try _.forOwn or _.forIn.

Sweet, thanks for the quick response! I wasn't aware of that nuance but that seems like a sensible design decision. _.forOwn() is exactly what I need!

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aj0strow picture aj0strow  路  3Comments

jasonkarns picture jasonkarns  路  3Comments

SameerSiddiqui picture SameerSiddiqui  路  3Comments

rtheunissen picture rtheunissen  路  3Comments

thoraage picture thoraage  路  3Comments