Search code examples
javascriptjavascript-objects

Last iteration in foreach loop with Object Javascript


I have an object like this.

objName {
 item1 : someItem,
 item2 : someItem,
 item3 : someItem,
}

Now the number of property is dynamic and can be increase in unknown amount, I am performing a foreach loop in the property key on this object like this.

Object.keys(objName).forEach(itemNumber => {
console.log(itemNumber);
});

How am I going to detect the very last iteration of it to perform a new task?


Solution

  • You could use index and array parameters to check if there is next element. You can also check if current index is equal length - 1 index == arr.length - 1

    let objName = {
     item1 : "someItem",
     item2 : "someItem",
     item3 : "someItem",
    }
    
    Object.keys(objName).forEach((item, index, arr) => {
      console.log(item);
      if(!arr[index + 1]) console.log('End')
    });