1

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?

Praveen
  • 55,303
  • 33
  • 133
  • 164
user580889
  • 67
  • 1
  • 3

6 Answers6

3

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"}]
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

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 = [];
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
0

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' };
Igor
  • 33,276
  • 14
  • 79
  • 112
0

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

Community
  • 1
  • 1
Rami
  • 7,162
  • 1
  • 22
  • 19
0

try this:

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

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

{
  "array": ["31":"123", "23":"456"]
}
BassT
  • 819
  • 7
  • 22