0

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.

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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).

Comments

0

// try this to sort employees by age

employees.sort(function(a, b){
 return a.age-b.age
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.