13

I have this object in JS:

var list = {134 : "A",140 : "B",131 : "C"}

I run it with:

jQuery.each(list, function(key, value) { 
console.log(key + " - " + value);
});

The output should be:

134 - A
140 - B
131 - C

But I dont know why, the output is:

131 - C
134 - A
140 - B

Any idea how can I fix it ?

Klian
  • 1,520
  • 5
  • 21
  • 32

4 Answers4

8

First off: that's not a list, it's an object. Object's order is not guaranteed to be kept - each implementation may choose a different ordering.

On the other hand, arrays do preserve order:

var list = [[134, "A"],[140, "B"],[131, "C"]];


jQuery.each(list, function(i, obj) { 
  console.log(i + " - " + obj[0] + " - " + obj[1]);
});
Steve Haley
  • 55,374
  • 17
  • 77
  • 85
Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
  • 1
    So how to disable sort? – fdrv Dec 11 '15 at 18:56
  • @fdrv you can't, it happened to the OP because the browser did sort the order of enumeration of the keys, like modern browser do. You can't restore original order by any other way than using an array like this answer truthly states instead of an object. – Kaddath Jan 10 '20 at 15:57
5

I bump into your question, and it took me 10 min to understand.

This is how you would solve your problem :

var list = {134 : "A",140 : "B",131 : "C"};

// 1 - property to list
list = Object.keys(list).map(
    function(key) {
         return { num : key , char : list[key]};;
     });

console.debug(list);
// 2 - sorting the list
var sorted = list.sort(function(a, b) {
            if(a.char < b.char) return -1; return 1;
        });

// 3 output
jQuery.each(sorted, function(index, obj) {      
        console.log(obj.num + " - " + obj.char);
});

JsFiddle: https://jsfiddle.net/wx38rz5L/1578/

Thomas
  • 5,603
  • 5
  • 32
  • 48
4

Object's properties do not have a defined order, as per the specification.

The mechanics and order of enumerating the properties (...) is not specified.

Source.

Therefore, ECMA implementations do not have to iterate in any order. In fact, the order varies in different browsers/versions.

alex
  • 479,566
  • 201
  • 878
  • 984
4

This happens because JavaScript object items do not have order.

In order to fix it you may use two arrays: one with the keys, and second with values:

var keys = [134, 140, 131],
    values = ["A", "B", "C"];

$.each(keys, function(i, key) {
    console.log(key, values[i]);
});
VisioN
  • 143,310
  • 32
  • 282
  • 281