0

I have a json object in occupancy_list as follows :

enter image description here

I am traversing the object as follows :

for(var prop in occupancy_list)
{
     console.log(prop);
}

I am getting values in reverse order. Like at first Room 2 then Room 1. How can I fix it ?

Rumel
  • 319
  • 1
  • 3
  • 19
  • 6
    Object properties are not guaranteed to come in any particular order. – Daniel Beck Jan 13 '16 at 16:42
  • 4
    Order is not guaranteed. If you want to guarantee order, use an array. – forgivenson Jan 13 '16 at 16:43
  • [The for...in statement iterates over the enumerable properties of an object, **in arbitrary order.**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) – j08691 Jan 13 '16 at 16:45
  • I think this could be the solution http://stackoverflow.com/questions/9762402/javascript-for-in-loop-but-in-reverse – Gianluca Paris Jan 13 '16 at 16:45
  • 1
    @Tanvir If you can allow ES6, use it. [It](http://www.2ality.com/2015/10/property-traversal-order-es6.html) makes this possible. (Or even better - the [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) object.) – Vidul Jan 13 '16 at 16:54

1 Answers1

0

Object properties are unsorted and could always be random. If you need order - get the keys, and iterate them that way:

Object.keys(occupancy_list).sort(function(a, b) {
   //sort logic
}).forEach(key) {
   //logic on each key
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • 1
    *"Object properties are unsorted and could always be random"*. That's not true anymore. For example for properties whose name isn't numeric, the insertion order is used for iterations. See http://www.2ality.com/2015/10/property-traversal-order-es6.html – Denys Séguret Jan 13 '16 at 16:44
  • @DenysSéguret -- Which part? – tymeJV Jan 13 '16 at 16:44
  • 3
    @DenysSéguret *anymore* - but what about older browsers? I think it'd be safer to assume they're not in order than the opposite. – SeinopSys Jan 13 '16 at 16:45