6

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?

4
  • The question is not clear 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. Commented Nov 21, 2018 at 13:41
  • the object length key here is 3 right? Commented Nov 21, 2018 at 13:41
  • Code updated sorry... Commented Nov 21, 2018 at 13:44

3 Answers 3

12

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')
});

Sign up to request clarification or add additional context in comments.

6 Comments

by subtracting the length to 1 means that is the last item?
If you have 3 elements then length is 3 but index of last element will be 2 because it starts from 0.
can I ask what is arr stands for?
array of what? object and array is different right, sorry I am not so familiar with javascript object and its method
Its a reference to the array that forEach is being applied to in this case its an array of object keys.
|
2

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]);
}
});

Comments

1

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");
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.