javascript - Destructuring key, value, and index of an object in es6 - Stack Overflow

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742265499a4411707.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信