I am trying to loop over a JavaScript object in ES6.
for (let [value, index] of object) {
do something with rest
if (index >= 1) {
// do something with first item
}
}
It works fine, although when I try to use index to get the first item it returns an error in console:
Uncaught TypeError: Invalid attempt to destructure non-iterable instance
Any ideas on how to loop over an object with index? thanks
This is just meant to be an addition to jonas w's solutions.
If you need the key of the current value:
Of course, you can leave out the
key
at any time:Simply count the index:
Or if you really want to use object destructuring ( i dont know why ) its a bit more complicated:
or:
But i dont know why youre not using a simple forEach?: