Given a key, I want to find the next property in an object. I can not rely on the keys to be ordered or sequential (they’re uuids). Please see below for trivial example of what I want:
var db = {
a: 1,
b: 2,
c: 3
}
var next = function(db, key) {
// ???
}
next(db, 'a'); // I want 2
next(db, 'b'); // I want 3
I also want a prev() function, but I’m sure it will be the same solution.
This seems like such a trivial problem but I can’t for the life of me figure out how to do it.
Happy for the solution to use underscore.js or be written in coffeescript 🙂
The correct answer is: you can’t do that, as objects are unordered as per ECMAScript’s spec.
I’d recommend that you use an ordered structure, like an array, for the purpose of the problem:
Then the
nextfunction can be something like:In case
keydoes not exist ondbor it was the last one,nextreturnsundefined. if you’re never going to ask for the next of the last item, you can simplify that function by removing the ternary&&operator and returningdb[i + 1].valuedirectly.You can also use some of Underscore.js utility methods to make
nextsimpler:(in this case
nextcould returnfalsesometimes… but it’s still a falsy value :))Now, a more pragmatic answer could be that, as most browsers will respect the order in which an object was initialized when iterating it, you can just iterate it with a
for inloop as the other answers suggest. I’d recommend usingObject.keysto simplify the job of iterating over the array: