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?
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
}
}
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