4

I am new to javascript so please excuse me if its something obvious.

Lets say I have a for-in loop as follows...

for( var key in myObj ){

   alert("key :" + myObj[key] ); // accessing current key-value pair

   //how do I access previous element here?
}

Is it possible to access previous or next key/value pair in for-in loop?

georg
  • 195,833
  • 46
  • 263
  • 351
Pratik Patel
  • 1,145
  • 16
  • 40

4 Answers4

5

No, there's no direct way. One workaround would be to use a for loop over keys instead of for..in and pick elements by their numeric index:

 keys = Object.keys(myObj);
 for(var i = 0; i < keys.length; i++) {
     current = keys[i];
     previous = keys[i - 1];
     next = keys[i + 1];
     ...
  }
georg
  • 195,833
  • 46
  • 263
  • 351
  • +1. Yes, I think I will use this method and drop for-in loop. I was expecting some straight-forward way to do this in for-in loop. – Pratik Patel Jul 12 '13 at 10:05
  • @PratikPatel: `for..in` is a bad idea anyways, so yes, do drop it. – georg Jul 12 '13 at 10:22
  • I wanted to avoid using Object.keys() function because of a comment in this answer http://stackoverflow.com/a/4889658/2039750 which says, "This not only iterates through the object but also creates a whole new array with all its keys..." – Pratik Patel Jul 12 '13 at 10:29
  • @PratikPatel: do not optimize prematurely. Unless your objects have millions of keys, making a new array doesn't matter at all. – georg Jul 12 '13 at 10:37
1
var lastobj = '';
for( var key in myObj ){
   alert("key :" + myObj[key] ); // accessing current key-value pair

   if(lastobj) {
        //do things with last object here using lastobjs
   }
lastobj = myObj[key]
}

Give a new value to lastobj last in loop and you will have the value "in memory" during the loop. The if statement is mostly because of the first loop run, when lastobj is empty yet.

Sergio
  • 27,160
  • 10
  • 79
  • 126
1

Couldn't you just say at the end of a loop something like:

previousKey = key

Then you can use previousKey in your next loop? This is something I do in my own small scripts, I'm by no means good at scripting but this has worked for me so far.

Sam
  • 11
  • 1
-1

Try like

var prev = '';
for( var key in myObj ){

   alert("key :" + myObj[key] ); // accessing current key-value pair
   if(prev)
      alert('Prev key :'+prev);
   prev = myobj[key];
   //how do I access previous element here?
}
Gautam3164
  • 27,319
  • 9
  • 56
  • 81