1

I have:

Object {12: Object, 13: Object, 14: Object}

and I want to detect the last for loop step in here:

for (var i in objs){
   console.log(objs[i]);
}

any ideas?

doniyor
  • 36,596
  • 57
  • 175
  • 260
  • what do you mean by *latest for loop step*? – AmmarCSE Aug 03 '15 at 15:20
  • The current loop step is always the latest ... Or do you mean you want to detect if you're executing the last step? – Teemu Aug 03 '15 at 15:21
  • Related: [How to efficiently count the number of keys/properties of an object in JavaScript?](http://stackoverflow.com/q/126100/464709) – Frédéric Hamidi Aug 03 '15 at 15:22
  • How do you define "last" ? -- I'm not sure that there are any guarantees of orders of attribute in an object. – Soren Aug 03 '15 at 15:24
  • @Soren just the last step before ending the loop – doniyor Aug 03 '15 at 15:25
  • @Soren You're right, but the order doesn't matter, if OP just wants to know, when the body of the loop is executed last time before exiting the loop. – Teemu Aug 03 '15 at 15:26

4 Answers4

2

you could use standard object method Object.keys();

obj = {12: Object, 13: Object, 14: Object};
keys = Object.keys(obj);
console.log(keys[keys.length - 1]);
console.log(obj[keys[keys.length - 1]]);//if you want that last ..
maioman
  • 18,154
  • 4
  • 36
  • 42
0

I hope this what you want

var latest;
for (var i in objs){
    console.log(objs[i]);
    latest = objs[i];
}
//work with latest
Elheni Mokhles
  • 3,801
  • 2
  • 12
  • 17
  • 2
    Im not sure, but i think you dont even need to set "latest", `i` is still set to be the last key of the loop so you can just use obj[i] after your loop. – Werring Aug 03 '15 at 15:25
0

Since you cannot control properties' order of an object (they come in arbitrary order which you cannot define) the whole idea probably loses some, or most, if not all, of its relevance.

If you don't actually care which property is being processed in that last loop step, here's an example of how you could go:

var objs = {12: Object, 13: Object, 14: Object};
var c = 0;
var objsKeys = Object.keys(objs); [12, 13, 14]
for (var i=0; i<obsjKeys.length, i++){
    if (i===(obsjKeys.length -1)) {
        console.log("Last Run of the Loop:");
    }
    console.log(objs[obsjKeys[i]]);
}

Object.keys() is only available since ES5, which means IE < 9 will not support it. In that case you can do your own implementation of it using for..in:

Object.keys = Object.keys || function(obj) {
    var tempArray = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            tempArray.push(key);
        }
    }
    return tempArray;
};
connexo
  • 53,704
  • 14
  • 91
  • 128
-2
Object.length - 1

This will give you the last element..

Dharmesh
  • 52
  • 1
  • 6