Reputation: 67
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
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
Reputation:
try this:
var objList = [];
objList.push({"31" : "123"});
objList.push({"23" : "456"});
alert(JSON.stringify(objList));
Upvotes: 0
Reputation: 849
You need to put the key-value pairs in an array so you get
{
"array": ["31":"123", "23":"456"]
}
Upvotes: -1
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
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
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