admin管理员组

文章数量:1331888

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!

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!

Share asked Feb 22, 2020 at 1:05 BWeb303BWeb303 3031 gold badge7 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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);
});

本文标签: javascriptDestructuring keyvalueand index of an object in es6Stack Overflow