user580889
user580889

Reputation: 67

How to get correct order of js object?

I have the question about js obj order:

When I define:

var objJSON = {};
objJSON[31] = '123'; ------------- (1)
objJSON[23] = '456'; ------------- (2)

And alert the object:

alert(JSON.stringify(objJSON, null, 4));

It shows:

    "
    {
       "23":"456",
       "31":"123"
    }
    "

    I would like to get the object by the order of inserting:
    "
    {
       "31":"123",
       "23":"456"
    }
    "

How to do so?

Upvotes: 1

Views: 190

Answers (6)

Elliot Bonneville
Elliot Bonneville

Reputation: 53311

JavaScript objects cannot be counted on to maintain order. You will likely want to use an array instead, which will preserve index order.

Just change {} to [] in your first line.

var objJSON = [];

Upvotes: 1

user2575725
user2575725

Reputation:

try this:

var objList = [];
objList.push({"31" : "123"});
objList.push({"23" : "456"});
alert(JSON.stringify(objList));

Upvotes: 0

BassT
BassT

Reputation: 849

You need to put the key-value pairs in an array so you get

{
  "array": ["31":"123", "23":"456"]
}

Upvotes: -1

Ja͢ck
Ja͢ck

Reputation: 173562

The properties of an object don't have a guaranteed ordering. If the key, value and position is important, I would recommend an array of objects instead:

var x = [];
x.push({
  key: 23,
  value: '123'
});
x.push({
  key: 31,
  value: '456'
});

JSON.stringify(x); // [{"key":23,"value":"123"},{"key":31,"value":"456"}]

Upvotes: 3

Rami
Rami

Reputation: 7290

A dictionary is a data structure that does not preserve order by definition. You will need to sort the dictionary yourself by key or by value.

Check this:

sort a dictionary (or whatever key-value data structure in js) on word_number keys efficiently

Upvotes: 0

Igor
Igor

Reputation: 33983

You're using an object (which can be thought of as a "map" for this purpose), when you need an array. Objects do not guarantee order. What if you happen to add another property later? It will also skew the order. Try using an array/list/vector of objects instead. For example:

var array = [];
array[0] = { 31: '123' };
array[1] = { 23: '456' };

Upvotes: 0

Related Questions