BWeb303
BWeb303

Reputation: 303

Destructuring key, value, and index of an object in es6

Can you destructure the key, value, and index of an object in a forEach?

I understand destructuring key and value would look like:

Object.entries(obj).forEach(([key, value]) => {
  ...
});

But I'm hoping to also destructure the index.

My attempt:

Object.entries(obj).forEach((entry, index) => {
    const [key, value] = entry;
    ...
});

But wasn't sure if there was a better way. I know this is a pretty basic question but thanks for the help!

Upvotes: 4

Views: 3637

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

Just list the index argument normally after destructuring the first argument:

Object.entries(obj).forEach(([key, value], index) => {

const obj = {
  foo: 'val'
};

Object.entries(obj).forEach(([key, value], index) => {
  console.log(key, value, index);
});

Upvotes: 10

Related Questions