Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over JavaScript object with index

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

like image 857
londonfed Avatar asked Jul 22 '17 06:07

londonfed


People also ask

How do I iterate over an object key?

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 do you get the index of an iteration in a for of loop in JavaScript?

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!

How do I iterate through a JSON object?

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.


Video Answer


1 Answers

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}`);  });
like image 178
PeterMader Avatar answered Oct 05 '22 19:10

PeterMader