0

I have a simple json object "obj" like this

var obj = {"a" : "x", "b" : "y", "c" : "z"}

I iterate through that object using the following code:

$.each(obj, function(index, element) {
    console.log("Now I'm at index " + index);
});

This of course produces series of:

Now I'm at index a
Now I'm at index b
Now I'm at index c

But what I'd like to see is:

Now I'm at index 0
Now I'm at index 1
Now I'm at index 2

But I cannot figure it out how to do it without having to use any additional variable that I'll need to increment in this loop.

Thanks in advance,

Matt Lishman
  • 1,817
  • 2
  • 22
  • 34
Lee
  • 11
  • 1
  • What would be wrong with using an additional counter variable? – Frédéric Hamidi Aug 04 '15 at 15:27
  • 1
    Thank you for bringing our attention to that wrong answer that attempts to apply `Object.keys()` to a JSON *string*. Six upvotes yet nobody thought to test that code. – Frédéric Hamidi Aug 04 '15 at 15:32
  • You can't. The order of an object is not guaranteed but the order of an array is. Therefore you don't have an index when iterating an object as you would not be able to retrieve data from the object with it. However with an array you would be able to. – Matt Derrick Aug 04 '15 at 15:44

1 Answers1

2

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

Community
  • 1
  • 1
Matt Lishman
  • 1,817
  • 2
  • 22
  • 34