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
You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.
How to Get the Index in a for…of Iteration. Use JavaScript's Array#entries method to create an array iterator. This iterator returns a key-value-pair for each index-value combination in the array. Enjoy!
Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.
This is just meant to be an addition to jonas w's solutions.
If you need the key of the current value:
const object = {a:2, b:4, c:6, d:8}; for (const [index, [key, value]] of Object.entries(Object.entries(object))) { console.log(`${index}: ${key} = ${value}`); } Object.entries(object).forEach(([key, value], index) => { console.log(`${index}: ${key} = ${value}`); });
Of course, you can leave out the key
at any time:
const object = {a:2, b:4, c:6, d:8}; for (const [index, [, value]] of Object.entries(Object.entries(object))) { console.log(`${index}: ${value}`); } Object.entries(object).forEach(([, value], index) => { console.log(`${index}: ${value}`); });
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