4

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 ?

Andy
  • 18,723
  • 12
  • 46
  • 54

2 Answers2

4

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++;}
Flavien Volken
  • 19,196
  • 12
  • 100
  • 133
4

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

Avinash
  • 2,003
  • 2
  • 17
  • 15