I’m parsing JSON and getting an array of objects with javascript. I’ve been doing this to then append an element for each object:
for(o in obj){ ... }
But I realized that for a certain situation I want to go backwards through the array. So I tried this before the for loop:
obj = obj.reverse();
However this isn’t reversing the order of the objects in the array. I could simply put a count variable in the for loop to manually get the reverse, but I’m puzzled as to why reverse doesn’t seem to work with object arrays.
There’s no such thing as an “object array” in JavaScript. There are Objects, and there are Arrays (which, of course, are also Objects). Objects have properties and the properties are not ordered in any defined way.
In other words, if you’ve got:
there’s no guarantee that a
for ... inloop will visit the properties in the order “a”, “b”, “c”.Now, if you’ve got an array of objects like:
then that’s an ordinary array, and you can reverse it. The
.reverse()method mutates the array, so you don’t re-assign it. If you do have an array of objects (or a real array of any sort of values), then you should not usefor ... into iterate through it. Use a numeric index.edit — it’s pointed out in a helpful comment that
.reverse()does return a reference to the array, so reassigning won’t hurt anything.