6
const obj = {
15: 100
};
for(let key in obj)
    console.log(key, typeof(key), typeof(+key))

The result is 15 string number. I'm trying to iterate over object values and put some of them into Map object but types compatibility seems unable to achieve. Am I doing something wrong here or object keys are always strings?

Object.keys(obj)

also returns ["15"]

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • 1
    because that is what they actually are. If you want them to be numbers, than map it to a number. `Object.keys(obj).map(k => +k)` – epascarello Aug 28 '18 at 14:39
  • Good guess, object keys are strings no matter you denote them with quotes or not. See the question: https://stackoverflow.com/questions/4348478/what-is-the-difference-between-object-keys-with-quotes-and-without-quotes – vahdet Aug 28 '18 at 14:39
  • Even an array's keys are, internally, strings: `console.log(Object.keys([1,2,3,4]));` – Cerbrus Aug 28 '18 at 14:43
  • Thanks for guiding me to the topic with explanation – Michał Grochowski Aug 28 '18 at 14:52

1 Answers1

7

Object keys are always strings. You can see more about it here:

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

For you to be able to achieve what you want you will need to cast the keys back to integers.

Pedro Henrique
  • 601
  • 6
  • 17