Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I loop through a javascript object in reverse order?

So I have a JavaScript object like this:

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

I can loop this like:

for (var i in foo) {   if (foo.hasOwnProperty(i)) {     // do something   } } 

Which will loop through the properties in the order of one > two > three.

However sometimes I need to go through in reverse order, so I would like to do the same loop, but three > two > one.

Question:
Is there an "object-reverse" function. If it was an Array, I could reverse or build a new array with unshift but I'm lost with what to do with an object, when I need to reverse-loop it's properties. Any ideas?

Thanks!

like image 252
frequent Avatar asked Sep 24 '13 09:09

frequent


People also ask

Can you loop through an object JavaScript?

Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.


1 Answers

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!

like image 50
Tibos Avatar answered Oct 02 '22 19:10

Tibos