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 ?
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++;}
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
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