Question

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?

Was it helpful?

Solution

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];
     ...
  }

OTHER TIPS

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.

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.

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?
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top