JavaScript or Node.js unexpectedly sort objects

Problem

When I running this code by node app.js

'use strict';

var data = {"456":"First","789":"Second","123":"Third"};

console.log(data);

I've geting next result:

{ '123': 'Third', '456': 'First', '789': 'Second' }

Why JS or Node.js (I don't know who) sort this object by keys? I don't want this.

Problem courtesy of: inetbug

Solution

What you're seeing is a behavior of the V8 JavaScript engine. It's not something specified by the JavaScript specification, and it's not something you can rely on (most engines don't do that).

But the important thing here is: There is no order to a JavaScript object. So V8's behavior is just as correct as putting those keys in any other order. If you want things in a particular order, you have to use an ordered container, like an array.

Solution courtesy of: T.J. Crowder

Discussion

Properties in an object aren't ordered. You can't expect the order you give to be preserved when a representation of your object is built for the console.

The iteration order is implementation dependent. Don't rely on it. If you need some order, use another data structure (for example and array of key-values).

Discussion courtesy of: Denys Séguret

JavaScript objects aren’t ordered. If you want things in order, you can use an array.

var data = [
    { key: "456", value: "First" },
    …
];

Or, alternatively, keep the key order in a separate array.

Discussion courtesy of: Ryan

// try this to sort employees by age

employees.sort(function(a, b){
 return a.age-b.age
});
Discussion courtesy of: fareed namrouti

This recipe can be found in it's original form on Stack Over Flow.