Object.entries problem!!

Object.entries on an array gives a string as the first argument of the resultant array.
The key of an array is meant to be a number. This is seriously frustrating!
Is there a work around??
eg:-

for(const [k, value] of Object.entries([1, 2, 3, 4])) {
      //then I have to do
     const key = Number(k)
    // this is obviously not cool!!
}

// I prefer a single expression for loop
for(const [k, value] of Object.entries([1, 2, 3, 4]))
    (k % 3 == 0) && (a_parallel_array[k +1] = value)

// this seriously results in a logical error
// What I get is not what I intended!

Any suggestions for better array enumerations with the classic for loop??

Array keys are strings, not numbers, because arrays are objects. Object.entries is doing the correct thing here.

However, you don't need to use Object.entries on an array at all - you can use .entries() to get an iterator for entry objects, where the indices will be numbers, or you can use all the array iteration methods and you'll get the index as an argument to the method callback.

5 Likes

.entries method seems like the right idea!!
Thanks @ljharb