Search code examples
javascriptjavascript-objects

Javascript Object [sorting]


If i use integer as a key in javascript object it shorts automatically.

var obj = {"z": 100, "x": 75, "d": 116, "c": 15, "10":123, "9":12}
console.log(obj)

Output:

{9: 12, 10: 123, z: 100, x: 75, d: 116, c: 15}

It is not maintaining sequence for integer, It works for alphabetical strings.

My question is Why it is so ? and how to overcome this if i need to manage sequence?


Solution

  • Object key ordering is not guaranteed. See Does JavaScript Guarantee Object Property Order?. Use an array of objects to guarantee ordering.

    var arr = [{"z":100}, {"x":75}, {"d":116}, {"c":15}, {"10":123}, {"9":12}]