0

Jquery + rails 4

In json_data instance i have some data with key and value, The key is an integer id and the value is an object which contains data.However when I try to iterate over this data with the jQuery $.each function, the results come back sorted by the key instead.How can I iterate over my collection of objects in their original order?

$.each(json_data, function(key, value){
 console.log(key);
      });

key = 6181 30654 39148 30743 30510 42998 5788 30401 ...//Mozilla Working Fine (Right)

key = 5788 6011 6181 30401 30510 30639 30654 30698 30743 ...// Chrome Not Working Fine (Wrong)

user3676578
  • 213
  • 1
  • 5
  • 17

1 Answers1

0

Regarding "order" in an object:

A JavaScript object is a hash table, and is optimized for constant time lookup of key:value pairs.

Arrays are a data structure in which the elements are assigned to a discrete index value. When you iterate over the elements of an array, you will return a predictable pattern that matches the order of the items in the array.

In an object however, there are no index values, so there is no constant predictable way to iterate over it in order. The object just stores key:value pairs that are optimized for constant-time lookup.

EDIT: I will demonstrate those two methods of iterating just for illustration, but I wanted to warn you in advance, they won't change the fact that you won't get the keys returned in a consistent order.

var json_data = {6181:true, 30654:true, 39148:true, 30743:true, 30510:true, 42998:true, 5788:true, 30401:true};
for(item in json_data){
  console.log(item);
} // *might* return a different order based on browser or JavaScript implementation

Clarifying one more time: objects are not associated with a particular 'order'. They are optimized to provide "constant time" lookup. Regardless of the size of the object, if you query a key, the associated value will be returned to you in constant time.

If you need to impose a particular order, you will need to use an array.

Example:

var json_data = [6181, 30654, 39148, 30743, 30510, 42998, 5788, 30401];

for(var i = 0; i < json_data.length; i++){
  console.log(json_data[i]);
}
// always returns the values in the same order they are in the json_data array.
// changing the order in the array will change the order they are output and
// and that order will be the same regardless of which browser or version of JavaScript you
// are using.
LexJacobs
  • 2,483
  • 15
  • 21
  • Iterate over an array with a for-with-semicolons loop. And iterate over the key values of an object with a for-in loop. – LexJacobs Jun 13 '14 at 14:52
  • var jsonData = {}; var newKey = 0; $.each(json_data, function(key, value){ newKey++; jsonData[newKey] = this; }); Not Working – user3676578 Jun 13 '14 at 15:06
  • Hello, if you found any of the answers useful, please select one as the official answer. Building reputations helps a lot on this site. Thank you! – LexJacobs Jun 18 '14 at 00:14