1

Suppose we have the following:

var o = {"1": 1, "2": 2, "5": 5};

And I wanted to turn it into what I would get if I did:

var o = []; o[1] = 1, o[2] = 2, o[5] = 5;

How could I do this?

1
  • o[5] == 5 is true for your original object. Commented Nov 20, 2013 at 12:45

3 Answers 3

1

Try this:

var o = { ... }; // your object
var oArr = [];
for (var i in o) {
    if (parseInt(i) == i) {
        oArr[parseInt(i)] = o[i];
    }
}

Notice that it won't accept keys that are non numeric.

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

Comments

1

If you have a proper length property, it's really easy:

var o = {"1": 1, "2": 2, "5": 5, 'length' : 6};
o = Array.prototype.slice.call(o); // [undefined, 1, 2, undefined, undefined, 5]

If you don't have the length property, you can compute it:

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]

One thing to note, though, when you access a property of an object, it is always converted to a string, so the following will work for your example, even if 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

Comments

0

You should not be doing that, 1. You are not sure about how big the maximum index value can be. 2. There could be lots of gaps, those indexes in the array will be null,

So, just use a string conversion of the index number and look it up in the same object.

 var o = {"1": 1, "2": 2, "5": 5};
 var index = 5;
 o[index.toString()]  // gives 5

1 Comment

No need for toString.

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.