JavaScript for a loop, but vice versa?

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 check 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 one (prop4 in this example). I am guessing I want a reverse-to-in-loop.

How can i do this?

Thanks Jack

Addendum: The object I am referring to is the one that was returned from JSON.parse. The properties appear to be ordered sequentially. There is no keys () method.

+3


source to share


3 answers


A for (x in y)

does not process properties in any particular order, so you cannot count on any ordering you want.

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

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

var keys = Object.keys(obj);

      



Then you can sort them in standard lexical order, or sort by your own custom function:

keys.sort(fn);

      

And then you can access them in the order you want:

for (var i = 0; i < keys.length; i++) {
    // process obj[keys[i]]
}

      

+12


source


Arrays are ordered objects. Properties in objects are inherently unordered. However, if you have some specific reason why you want to work from the beginning to what the construct would create for..in

, you could do:



var arr = [];
for (prop in obj) {
   arr.push(prop);
}

for (var n=arr.length; n--; ){
   var prop = obj[arr[n]];
}

      

+2


source


The ECMAScript standard does not define the iteration order for loops for in

. You will need an array if your data types are going to be sorted.

+1


source







All Articles