Javascript Object – Next and Previous Keys

I often need to perform “next” and “previous” operations on standard JavaScript objects or JSON objects. There is no built-in functionality to do this, so here are some helper functions I’ve created to perform these basic operations:

There is a caveat: The EcmaScript specification doesn’t define an order in which keys are returned in an object — unlike an array. However, all modern browsers (as of Feburary 2014) do return them in the order they are supplied.

Functions with mock data and tests:

See the Pen object keys next and previous by Michael Jasper (@mdjasper) on CodePen.

Author: Michael Jasper

Michael is a Web Developer located in Northern Utah. When not programming, he enjoys spending time with his family, exploring the great-outdoors, and hit-and-miss cooking experiments.

  • Fanee

    https://jsfiddle.net/bababalcksheep/48jyemu7/
    Fixed your code and updated a bit with loop

    //Mock data
    var data = {
    “a”: “first”,
    “b”: “second”,
    “c”: “third”,
    “d”: “forth”
    };

    //Object Helper Functions
    oFunctions = {};
    oFunctions.keys = {};

    //NEXT KEY
    oFunctions.keys.next = function(o, id, loop) {
    var keys = Object.keys(o);
    var idIndex = keys.indexOf(id);
    var nextIndex = idIndex + 1;
    if (nextIndex >= keys.length) {
    //we’re at the end, there is no next
    if (loop) {
    return keys[0];
    } else {
    return;
    }
    }
    var nextKey = keys[nextIndex]
    return nextKey;
    };

    //PREVIOUS KEY
    oFunctions.keys.previous = function(o, id, loop) {
    var keys = Object.keys(o);
    var idIndex = keys.indexOf(id);
    var nextIndex = idIndex – 1;
    //
    if (idIndex === 0) {
    //we’re at the beginning, there is no previous
    if (loop) {
    return keys.slice(-1)[0];
    } else {
    return;
    }

    }
    var nextKey = keys[nextIndex]
    return nextKey;
    };

    //Test helper function
    function p(a) {
    document.write(a + “”);
    }

    function _print(value,phrase,loop) {
    var what = oFunctions.keys[phrase](data, value, loop);
    document.write(value + ‘ → ‘ + what+ “”);
    }
    //Tests
    p(‘======= next without loop ========= ‘);
    _print(‘a’,’next’);
    _print(‘d’,’next’);
    p(‘======= next with loop ========= ‘);
    _print(‘a’,’next’,true);
    _print(‘d’,’next’,true);
    p(‘======= previous without loop ========= ‘);
    _print(‘a’,’previous’);
    _print(‘d’,’previous’);
    p(‘======= previous with loop ========= ‘);
    _print(‘a’,’previous’,true);
    _print(‘d’,’previous’,true);

    // END