Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript for in loop, but in reverse?

Taking a JavaScript object with 4 properties:

function Object() {
  this.prop1;
  this.prop2;
  this.prop3;
  this.prop4;
}

var obj = new Object();

I use a for(in) loop to inspect each property since I don't know the number or name of the properties:

for(property in obj) {
  var prop = obj[property];
}

However I would like to process the properties starting with the last (prop4 in this example). I suppose I would like a reverse-for-in-loop.

How can I do this?

Thanks, Jack

Adding: The object I am referring to is the one returned from JSON.parse. The properties seem to be consistently ordered. There is no keys() method.

like image 753
Jack Avatar asked Mar 18 '12 21:03

Jack


People also ask

How do you reverse a loop?

To reverse for loop in Python just need to read the last element first and then the last but one and so on till the element is at index 0. You can do it with the range function, List Comprehension, or reversed() function.

Why reverse for loop is faster?

Backwards for loop is faster because the upper-bound (hehe, lower-bound) loop control variable does not have to be defined or fetched from an object; it is a constant zero. There is no real difference. Native loop constructs are always going to be very fast.

How do you reverse an array forEach loop?

To use the forEach() method on an array in reverse order:Use the slice() method to get a copy of the array. Use the reverse() method to reverse the copied array. Call the forEach() method on the reversed array.


2 Answers

A for (x in y) does not process the properties in any specific order so you cannot count on any desired order.

If you need to process the properties in a specific order, you will need to get all the properties into an array, sort the array appropriately and then use those keys in the desired order.

Using ES5 (or an ES5 shim), you can get all properties into an array with:

var keys = Object.keys(obj);

You could then sort them either in standard lexical order or sort with your own custom function:

keys.sort(fn);

And, then you could access them in your desired order:

for (var i = 0; i < keys.length; i++) {
    // process obj[keys[i]]
}
like image 111
jfriend00 Avatar answered Sep 17 '22 23:09

jfriend00


The ECMAScript standard does not define an order to iteration for for in loops. You will want an array, if your datatypes are to be sorted.

like image 45
dwerner Avatar answered Sep 18 '22 23:09

dwerner