JavaScript casts keys with numerical strings to Numbers... but Object.keys() doesn't
Your problem is for in
for in tries to access keys in array created by Object.keys(obj.data)
which is actually index
let obj = {"data": {"1.0": 'foo',"2.3": 'bar',"3.6": 'baz'}}
Object.keys(obj.data).forEach(e=>{
console.log(typeof e)
})
//You can simply drop of Object.keys
for (let k in obj.data) {
console.log(k, obj.data[k])
}
Simply do not use Object.keys
:
let myObject = {
"data": {
"1.0": 'foo',
"2.3": 'bar',
"3.6": 'baz'
}
}
console.log(myObject.data)
for (let k in myObject.data) {
console.log(k, myObject.data[k])
}
Some explanation:
Object.keys
does what it says - extracts keys from the passed in object and returns them as array (in your case that'd be: [ "1.0", "2.3", "3.6"]
). So when you are trying to loop over this with for..in
, you are in fact looping over that resulting array, instead of the actual object and key
variable will receive an index of the corresponding item from the array (0
for "1.0"
, 1
for "2.3"
, etc). That's just how for..in
works. If you would like to loop over the values of the array instead, you could use for..of
as another option. Or in your case, as I've mentioned above, simply do not use Object.keys
.
The problem is with the for..in
loop, try for..of
to solve this issue. The for..in
loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype.
Whereas for..of
on the other hand, is mainly interested in values of iterable objects in this case it is an array returned by the Object.keys()
call.
var myObject = {
"data": {
"1.0": 'foo',
"2.3": 'bar',
"3.6": 'baz'
}
}
console.log(myObject.data)
for (let k of Object.keys(myObject.data)) {
console.log(k, myObject.data[k])
}
Here when you are iterating through the Object.keys(myObject.data)
, it is considering the indices(keys of array object) of the returned array instead of the actual values of myObject.data
array.
Here is the distinction with a small example:
var arr = [10, 20, 30];
console.log("**for - in loop**")
//logs indices 0, 1, 2
for (i in arr){
console.log(i);
}
console.log("**for - of loop**")
//logs values in the array 10, 20, 30
for (i of arr){
console.log(i);
}