0

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.

3 Answers 3

2

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

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

2 Comments

Don't use for...in for arrays. The iteration order is just as undefined as it for an object, and will also return methods added to Array.prototype.
@Tim-Down You're right. I wrote the scripts above just for demonstration. Some js frameworks would inject functions into Array's prototype. But I don't think it is a good js citizen should do :). The classical for var i & less than length loop is recommended anyway.
1

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);
});

Comments

1

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]]);
}

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.