Reputation: 821
I have the following JSON:
var somearr = {
"08":{val:blabla,val:blabla},
"09":{val:blabla,val:blabla},
"10":{val:blabla,val:blabla},
"11":{val:blabla,val:blabla},
...
"14":{val:blabla,val:blabla}
}
when doing
for ( i in somearr) {
console.log(i);
}
I got this sequence: 10, 11, ... 14, 08, 09
How can the original sort order be achieved?
Thanks in advance for help.
Upvotes: 0
Views: 634
Reputation: 324567
The iteration order of properties using for...in
is specified as being implementation-specific, and browsers do vary. Therefore if you need a particular order, you must use an array, which you can then sort and iterate over using a for
loop. Here's how you can do it:
var keys = [];
for (var name in somearr) {
if (somearr.hasOwnProperty(name)) {
keys.push(name);
}
}
keys.sort();
for (var i = 0; i < keys.length; ++i) {
console.log(keys[i] + "=>" + somearr[keys[i]]);
}
Upvotes: 1
Reputation: 3595
Put the keys into an array, sort it, then iterate over it, and pull from the object.
Using Underscore.js:
var keys = _.keys(somearr).sort();
_.each(keys, function(key) {
var value = somearr[key];
console.log(value);
});
Upvotes: 1
Reputation: 761
The type of somearr you defined is a map(dict) not an array. You can define an array by using [] e.g.
var somearr = [{val:blabla,val:blabla}, {val:blabla,val:blabla}, {val:blabla,val:blabla}];
for(var i in somearry) {
console.log(i);
}
You'll get what you want
Upvotes: 2