Iterate over JavaScript object with index

后端 未结 2 618
小鲜肉
小鲜肉 2020-12-15 20:49

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 s         


        
2条回答
  •  囚心锁ツ
    2020-12-15 21:16

    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)=> /*...*/);
    

提交回复
热议问题