Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Object.keys is returns array of string instead of array of Numbers

Tags:

javascript

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?

like image 891
Jagdish Idhate Avatar asked May 30 '16 14:05

Jagdish Idhate


People also ask

Can object keys be numbers?

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.

Does object keys work on arrays?

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.

Does object keys convert to string?

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]" .

How do you assign an array to an object key?

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.


1 Answers

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);
like image 136
dfsq Avatar answered Sep 19 '22 22:09

dfsq