Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through javascript object converts keys to string [duplicate]

Tags:

javascript

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]

like image 984
user4150760 Avatar asked Aug 17 '15 20:08

user4150760


People also ask

Does object keys convert to string?

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.

Can you loop through an object JavaScript?

Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.

Can JavaScript object have same keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

How do you turn an object into a string in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);


1 Answers

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

like image 190
meagar Avatar answered Nov 12 '22 15:11

meagar