Is there a forEach
loop in Lodash
for associative arrays? The function called "forEach", I've found, only works for indexed arrays. For example, if I have an array myArray
with values [1, 2, 3]
, and do
lodash.forEach(myArray, function(index) {
console.log(index);
});
and run the function (in Node
), I get the expected result:
1
2
3
However, when I try this with an associative array, it doesn't work:
lodash = require('lodash');
myArray = [];
myArray['valOne'] = 1;
myArray['valTwo'] = 2;
myArray['valThree'] = 3;
lodash.forEach(myArray, function(index) {
console.log('7');
});
As you can see from running this in Node
, the callback function doesn't fire even when it includes something other than the array elements. It just seems to skip the loop entirely.
First of all, why does this happen? Second of all, is there another function included in Lodash
for this problem, or, if not, is there a way to use the forEach
function to accomplish this, without changing the original array in the process?
Lodash
has the function forOwn
for this purpose. In the second array, if you do
_.forOwn(myArray, function(index) {
console.log(index);
});
you should get the intended result.
I'm still not sure why forEach
seems to skip the first function, however, but I believe it may have to do with the array not having a "length". A JavaScript
array's length is the highest numbered index it has. For example, an array myOtherArray
defined as myOtherArray[999]="myValue"
will have a length of 1,000 (because arrays are zero-indexed, meaning they start at 0, not 1), even if it has no other values. This means an array with no numbered indexes, or only negative indexes, will not have a length
attribute. Lodash
must be picking up on this and not giving the array a length
attribute, likely to maintain consistency and performance, thus not rendering any output.
myArray = [];
myArray['valOne'] = 1;
myArray['valTwo'] = 2;
myArray['valThree'] = 3;
lodash.forEach(myArray, function(index) {
console.log('7');
});
An associative array is just a set of key value pairs, which is nothing but a Javascript object.
Above case - myArray.length === 0
,
You are just addding properties to the array object, not adding any values to actual array.
Instead initialize your myArray like this and loop through using forIn
var myArray = {};
myArray['valOne'] = 1;
myArray['valTwo'] = 2;
myArray['valThree'] = 3;
lodash.forIn(myArray, function(value, key) {
console.log(key + " : " + value);
});
OR just
var myArray = {
valOne : 1,
valTwo : 2,
valThree : 3
};
lodash.forIn(myArray, function(value, key) {
console.log(key + " : " + value);
});
More about Object as Associative Array here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With