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?
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?
Share Improve this question edited Nov 21, 2018 at 13:58 Mihae Kheel asked Nov 21, 2018 at 13:37 Mihae KheelMihae Kheel 2,6513 gold badges19 silver badges41 bronze badges 4- The question is not clear – brk Commented Nov 21, 2018 at 13:38
- i need to detect the very last iteration like declaring a var number that will increment while the length of object's property is equal to var number but since I am new javascript object I do not know where to start. – Mihae Kheel Commented Nov 21, 2018 at 13:41
- the object length key here is 3 right? – Mihae Kheel Commented Nov 21, 2018 at 13:41
- Code updated sorry... – Mihae Kheel Commented Nov 21, 2018 at 13:44
3 Answers
Reset to default 12You 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')
});
You can pass index and value to forEach function like the code below and use Object.keys(objName).length to get the object length then the last member objName[value]
var objName = {
item1 : "someItem",
item2 : "someItem",
item3 : "someItem3",
}
Object.keys(objName).forEach((value, index) => {
if(index==Object.keys(objName).length-1){
console.log(objName[value]);
}
});
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");
}
});