The keys that an object holds can be retrieved as an array with Object.keys(<var>)
. The order of the keys in the array is arbitrary; you need to sort them before indexing. An option is the built-in sort()
method for arrays, which is especially useful because custom comparison functions can be provided (see below). Default order is alphabetical.
Once you get the ordered array, you only need to look up where your item is in the array and return the next and previous elements from it:
var keys = Object.keys(items).sort();
var loc = keys.indexOf(item);
Given that loc > -1
(that is, the item exists):
- Previous item:
items[keys[loc-1]]
, but check that loc > 0
(it's not the first one).
- Next item:
items[keys[loc+1]]
, but check that loc < keys.length
(it's not the last one).
Object.keys
is compatible with Javascript 1.85+; here is a workaround for older browsers.
Alternative orderings
Numerical
If you want the keys to have a numerical order, use this comparison function:
var keys = Object.keys(items).sort( function(a,b) {
return b - a;
});
Creation (or Modification) Time
If you want to work with creation order instead of alphanumeric, the items must hold their creation time. Something like:
<value>.index = Date.getTime();
items['<item>'] = <value>;
Then, the sort()
method needs the following comparison function:
var keys = Object.keys(items).sort( function(a,b) {
return b.index - a.index;
});
This can be easily extended to last modification ordering or similar.
Creation Order
Notice that the former solution only works if the items are created more than 1 ms apart, which would be suitable for user actions. If the items are added faster, use this instead of the timestamp:
<value>.index = Object.keys(items).length;
Or, alternatively, keep an external counter with the number of items in the object.