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]
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.
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.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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]"
.
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