Can I loop through a javascript object in reverse order?

Solution 1:

Javascript objects don't have a guaranteed inherent order, so there doesn't exist a "reverse" order.

4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Browsers do seem to return the properties in the same order they were added to the object, but since this is not standard, you probably shouldn't rely on this behavior.

A simple function that calls a function for each property in reverse order as that given by the browser's for..in, is this:

// f is a function that has the obj as 'this' and the property name as first parameter
function reverseForIn(obj, f) {
  var arr = [];
  for (var key in obj) {
    // add hasOwnPropertyCheck if needed
    arr.push(key);
  }
  for (var i=arr.length-1; i>=0; i--) {
    f.call(obj, arr[i]);
  }
}

//usage
reverseForIn(obj, function(key){ console.log('KEY:', key, 'VALUE:', this[key]); });

Working JsBin: http://jsbin.com/aPoBAbE/1/edit

Again i say that the order of for..in is not guaranteed, so the reverse order is not guaranteed. Use with caution!

Solution 2:

Why there is no one has mentioned Object.keys() ?

you can get Array of Object's properties ordered as it is, then you can reverse it or filter it as you want with Array methods .

let foo = {
  "one": "some",
  "two": "thing",
  "three": "else"
};

// Get REVERSED Array of Propirties
let properties = Object.keys(foo).reverse();
// "three"
// "two"
// "one"

// Then you could use .forEach / .map
properties.forEach(prop => console.log(`PropertyName: ${prop}, its Value: ${foo[prop]}`));

// PropertyName: three, its Value: else
// PropertyName: two, its Value: thing
// PropertyName: one, its Value: some