The problem of a reversible array of objects with JS

I parse JSON and get an array of objects with javascript. I did this to add an element for each object:

for(o in obj){ ... } 

But I realized that for a specific situation, I want to go back through the array. So I tried this before the for loop:

 obj = obj.reverse(); 

However, this does not reverse the order of the objects in the array. I could just put the count variable in a for loop to manually get the opposite, but I'm puzzled why the opposite doesn't work with arrays of objects.

+4
source share
2 answers

There is no such thing as an "array of objects" in JavaScript. There are objects, and there are arrays (which, of course, are also objects). Objects have properties and properties are not ordered in any particular way.

In other words, if you have:

 var obj = { a: 1, b: 2, c: 3 }; 

there is no guarantee that the for ... in loop will visit properties in the order "a", "b", "c".

Now, if you have an array of objects such as:

 var arr = [ { a: 1 }, { b: 2 }, { c: 3 } ]; 

then it is a regular array and you can undo it. The .reverse() method mutates the array, so you do not reinstall it. If you have an array of objects (or a real array of any values), then you should not use for ... in to iterate through it. Use a numeric index.

edit - he indicated in a useful comment that .reverse() returns a reference to the array, so reassigning will not hurt anything.

+10
source

This is because for (o in obj) does not iterate over the array as an array, but as an object. It iterates over the properties of an object, which also includes elements in the array, but they are repeated in the order of the name, and not in the order that you placed in the array.

In addition, you are using the reverse method incorrectly. It changes the array in place, so do not use the return value:

 obj.reverse(); 
+2
source

Source: https://habr.com/ru/post/1401399/


All Articles