Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore forEach index?

I have an object that contains the follow structure

{
Apples: Array[1],
Mangos: Array[2],
Oranges: Array[5],
Bananas: Array[11]
}

These values are extracted using a

_.forEach(contents, function(values, key) {

}

Where the key = apples and the values would be the array. I am wondering how I can get the current index within this foreach loop ?

i.e. so I get 1,2,3,4 ? There may not be a way to do this other than to push them to an array ?

like image 511
Andy Avatar asked Feb 17 '23 09:02

Andy


2 Answers

I'm not sure that I completely got your question, but if you are looking for the index of the item currently enumerated here is a way using the "_forEach" equivalent

var test = {"a":"foo", "b":"bar"}
var index = 0;
for (key in test){ alert(key +"is at "+index+" position"); index++;}
like image 200
Flavien Volken Avatar answered Mar 03 '23 01:03

Flavien Volken


Try this:

_.each(myArray,function(eachItem,index){
       console.log("item: "+ eachItem + "at index " + index);
    }

Example:

var myArr = [
Apples: "One",
Mangos: "Two",
Oranges: "Three",
Bananas: "Four"
]

_.each(myArr,function(eachItem,index){
       console.log("item: "+ eachItem + "at index " + index);
    }

Output:

item:One at index 0

item:Two at index 1

item:Three at index 2

item:Four at index 3

Reference: Underscore JS Reference Link

like image 37
Avinash Avatar answered Mar 03 '23 02:03

Avinash