Taken from this SO answer:
If the order of the objects is significant, you should revise your JSON schema to store the objects in an array:
As Ben Alpert points out, properties of Javascript objects are unordered, and your code is broken if you expect them to enumerate in the same order that they are specified in the object literal—there is no "first" property.
Objects are not ordered, don't expect them to be.
EDIT: I noticed you don't want to use a variable to increment. So here is another solution.
Store your objects in an array, then loop through that array.
var arrayOfObjects = [
{"a" : "x"},
{"b" : "y"},
{"c" : "z"}
]
$.each(arrayOfObjects, function(index, object){
console.log('index', index);
console.log('object', object);
})
Notice how i've change the arrayOfObjects
slightly.
This will produce:
index 0
object Object {a: "x"}
index 1
object Object {b: "y"}
index 2
object Object {c: "z"}
Original Answer (In case this is useful to anyone else):
You should just use a variable in your function.
var index = 0;
$.each(obj, function(key, value) {
console.log("Now I'm at index " + index);
index++;
});
Notice how i'm using (key,value)
now instead of (index,element).
On jQuery's each documentation they mention:
If an object is used as the collection, the callback is passed a key-value pair each time:
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
Once again, this produces two messages:
flammable: inflammable
duh: no duh