Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over object, knowing when you're on the last iteration

Tags:

javascript

I need to iterate over an Object, but know when I'm on the last iteration. How can I do that? Objects don't have a "length" attribute, so I can't just count the iteration number and compare it to the length. I'm 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?

like image 726
Martin C. Martin Avatar asked Dec 27 '22 15:12

Martin C. Martin


1 Answers

You can find the number of keys using:

var n = Object.keys(obj).length

On pre-ES5 browsers a shim is available on the MDN website.

A possible solution to your problem is this:

var keys = Object.keys(obj);
while (keys.length) {

    var key = keys.shift();
    var value = obj[key];

    if (!keys.length) {
        // this is the last key
    }
}
like image 85
Alnitak Avatar answered Dec 29 '22 07:12

Alnitak