Iterate over JavaScript object with index

2020-03-01 12:21发布

问题:

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

回答1:

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



回答2:

Simply count the index:

let index = 0;
for (let value of object) {
  //do something with rest
  if (index >= 1) {
    // do something with the third and following items
  }
  index++;
}

Or if you really want to use object destructuring ( i dont know why ) its a bit more complicated:

let entries = Object.entries(object);

for(let [index, [key, value]] of entries.entries()){
 //...
}

or:

for(let [index,value] of Object.values(object).entries()){
  //...
}

But i dont know why youre not using a simple forEach?:

Object.values(obj).forEach((value, index)=> /*...*/);