Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 622
Mihae Kheel Avatar asked Nov 21 '18 13:11

Mihae Kheel


2 Answers

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')
});
like image 125
Nenad Vracar Avatar answered Nov 17 '22 04:11

Nenad Vracar


First find the length of the object like below:

var objLength= Object.keys(objName).length;

Then you can use like this:

var count = 0;

Object.keys(objName).forEach(item => {
    console.log(item);
    count++;
    if (count == objLength)
    {
        console.log("endOfLoop");
    }
});
like image 1
Aparna Avatar answered Nov 17 '22 03:11

Aparna