Iterate over the object, knowing when you are at the last iteration

I need to iterate over an object, but I know when I am at the last iteration. How can i do this? Objects do not have a length attribute, so I can’t just calculate the iteration number and compare it with the length. I am tempted to do something like

var len = 0; for ( key in obj ) { len++; } var i = 0; for ( key in obj ) { i++; var last_iter = (i == len); ... } 

Is there a better way?

+4
source share
3 answers

You can find the number of keys using:

 var n = Object.keys(obj).length 

In pre-ES5 browsers on the website

+8
source

If you need to do something with the last key, you can simply set it to a variable and use it after the loop. This will save the cycle by half.

 var key = ''; for (key in obj) { //... } // Operation with last key... // obj[key]; 
+2
source
 var prev_key = false; for (key in obj) { if(prev_key) { <code here> } prev_key = key; } <code here for last key> 

This code would work better if you could get the first key of the object, so you could avoid if, but you cannot do it reliably in javascript (and still iterate in the same order in the loop).

0
source

Source: https://habr.com/ru/post/1443540/


All Articles