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?
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')
});
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");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With