12

When I loop through an object in Javascript to extract its keys, why do the keys convert to string when they were intended to be integers ?

obj = {1:'a', 2:'b'};
arr = [];
for(var key in obj){
  if (obj.hasOwnProperty(key)){
    arr.push(key);
  }
}

Now arr is [ "1", "2" ] instead of [1, 2]

user4150760
  • 2,739
  • 5
  • 18
  • 25
  • not really your question, but in case you want your object's keys: in more recent versions of JavaScript, this can be done directly with [Object.keys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) – amenthes Aug 17 '15 at 20:18
  • @amenthes I saw that somewhere, however I'm unsure of browser support for this fn – user4150760 Aug 17 '15 at 20:21
  • 1
    depends on you userbase, but the "last two" browsers implement it across the board. For questions like this, i like to refer to http://caniuse.com/#search=keys – amenthes Aug 17 '15 at 20:23

2 Answers2

25

It's not the loop that is converting the keys; it's the fact that keys can only be strings. You cannot have any other type of key. If your key isn't a string, JavaScript will convert it to a string when you use it as a property name.

Consider:

key = {
  toString: function () { return "Blah" }
};

myObject = {}

myObject[key] = "value";

// writes "Blah"
document.write(Object.keys(myObject));

Note that if you didn't provide a toString, the keys would have been the string "[object Object]".

user229044
  • 232,980
  • 40
  • 330
  • 338
  • Point noted. Though this answer made me think that string keys only matter when using JSON : http://stackoverflow.com/q/4348478/4150760 – user4150760 Aug 17 '15 at 20:19
-2

what meagar says is correct, but if for some reason you want numbers you can convert them prefixing with a plus;

obj = {1:'a', 2:'b'};
arr = [];
for(var key in obj){
  if (obj.hasOwnProperty(key)){
    arr.push(+key);
  }
}

console.log(arr)

that said , you maybe interested in looking into Object.keys method

maioman
  • 18,154
  • 4
  • 36
  • 42