When I run following code
var obj = { 0: 'a', 1: 'b', 2: 'c' }; typeof Object.keys(obj)[0] //returns string
In obj
object i'm creating Number keys.
Any reason, why its string and not a number
?
Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.
The Object. keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
If your key isn't a string, JavaScript will convert it to a string when you use it as a property name. Note that if you didn't provide a toString , the keys would have been the string "[object Object]" .
To convert an array's values to object keys:Declare a new variable and set it to an empty object. Use the forEach() method to iterate over the array. On each iteration, assign the array's element as a key in the object.
Keys are always of a String type. If you need numbers you will have to cast them manually:
var obj = { 0: 'a', 1: 'b', 2: 'c' }; var ids = Object.keys(obj).map(Number); console.log(ids);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With