If you possess a valid length property, handling it is quite simple:
var o = {"1": 1, "2": 2, "5": 5, 'length' : 6};
o = Array.prototype.slice.call(o); // [undefined, 1, 2, undefined, undefined, 5]
In case the length property is absent, you can calculate it as follows:
var o = {"1": 1, "2": 2, "5": 5};
o.length = Object.keys(o).reduce(function(max,key){
return isNaN(key) ? max : Math.max(max, +key);
},-1) + 1;
o = Array.prototype.slice.call(o); // [undefined, 1, 2, undefined, undefined, 5]
It's important to keep in mind that when accessing an object's property, it gets automatically converted to a string. This means that the following will work for your instance, regardless of whether o
is not an array:
var o = {"1": 1, "2": 2, "5": 5};
o[1] // 1
o[2] // 2
o[5] // 5
o[0] // undefined