Lodash for each associative array

Is there a forEach loop in Lodash for associative arrays? A function called "forEach", I discovered, works only 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 does not 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 does not work even if it contains something other than array elements. It seems he just missed the loop.

First of all, why is this happening? Secondly, is there another function included in Lodash for this problem, or, if not, is there a way to use the forEach to execute it without changing the original array in the process?

+7
javascript arrays foreach lodash
source share
2 answers

Lodash has a forOwn function for this. In the second array, if you do

 _.forOwn(myArray, function(index) { console.log(index); }); 

You should get the expected result.

I'm still not sure why forEach seems to skip the first function, but I suppose this might be related to an array that doesn't have a "length". The length of the JavaScript array is the highest numbered index. For example, the array myOtherArray , defined as myOtherArray[999]="myValue" , will be 1000 (because the arrays are null-indexed, that is, they start at 0, not 1), even if it has no other values. This means that an array without numbered indices or only negative indices will not have the length attribute. Lodash should pick this value and not give an array a length attribute, which is likely to maintain consistency and performance, so it will not output any output.

+5
source share
 myArray = []; myArray['valOne'] = 1; myArray['valTwo'] = 2; myArray['valThree'] = 3; lodash.forEach(myArray, function(index) { console.log('7'); }); 

An associative array is just a collection of key value pairs that is nothing more than a Javascript object. The above case is myArray.length === 0 , you just add properties to the array object without adding any values ​​to the actual array.

Instead, initialize myArray this way and loop through with forIn

 var myArray = {}; myArray['valOne'] = 1; myArray['valTwo'] = 2; myArray['valThree'] = 3; lodash.forIn(myArray, function(value, key) { console.log(key + " : " + value); }); 

Or simply

  var myArray = { valOne : 1, valTwo : 2, valThree : 3 }; lodash.forIn(myArray, function(value, key) { console.log(key + " : " + value); }); 

More information about the object as an associative array here

+6
source share

All Articles