Octopus
Octopus

Reputation: 8325

How do I walk through an object's keys in a consistent order?

I have a js object that looks something like this:

var obj = {
  '1001' : [...data...],      
  '1002' : [...data...],      
  '1003' : [...data...],
  '1004' : [...data...],
  '1005' : [...data...],
  '1006' : [...data...],
}

And when I do this:

for (var i in obj) {
  console.log(i);
}

I get unpredictable order in Firefox. In other words, for most browsers I get the following logged to console:

1001
1002
1003
1004
1005
1006

But Firefox does something more like this:

1006
1003
1001
1002
1005
1004

How can I walk through the object's arrays and know for sure that I am getting them in the right order.

Also to make it more complicated the keys might not be in sequential order and might not all be integers.

Upvotes: 1

Views: 280

Answers (2)

MinusFour
MinusFour

Reputation: 14423

If you need to iterate it respecting insertion order you could use a Map instead of an Object.

var m = new Map();
m.set(1001, ..);
m.set(1002, ..);

for(var [key, val] of m){
   //iteration in order of insertion
}

Upvotes: 1

Jacob
Jacob

Reputation: 78900

Object keys have no defined order. You'd have to explicitly sort:

Object
  .keys(obj)
  .sort()
  .forEach(function (key) {
    console.log(key);
  });

Upvotes: 8

Related Questions