Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The correct answer is: you can't do that, as <a href="https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order">objects are unordered as per ECMAScript's spec</a>.</p> <p>I'd recommend that you use an ordered structure, like an array, for the purpose of the problem:</p> <pre><code>var db = [ {key: 'a', value: 1}, {key: 'b', value: 2}, {key: 'c', value: 3} ]; </code></pre> <p>Then the <code>next</code> function can be something like:</p> <pre><code>var next = function(db, key) { for (var i = 0; i &lt; db.length; i++) { if (db[i].key === key) { return db[i + 1] &amp;&amp; db[i + 1].value; } } }; </code></pre> <p>In case <code>key</code> does not exist on <code>db</code> or it was the last one, <code>next</code> returns <code>undefined</code>. if you're never going to ask for the next of the last item, you can simplify that function by removing the ternary <code>&amp;&amp;</code> operator and returning <code>db[i + 1].value</code> directly.</p> <p>You can also use some of Underscore.js utility methods to make <code>next</code> simpler:</p> <pre><code>var next = function(db, key) { var i = _.pluck(db, 'key').indexOf(key); return i !== -1 &amp;&amp; db[i + 1] &amp;&amp; db[i + 1].value; }; </code></pre> <p>(in this case <code>next</code> could return <code>false</code> sometimes... but it's still a falsy value :))</p> <hr> <p>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 <code>for in</code> loop as the other answers suggest. I'd recommend using <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys" rel="nofollow noreferrer"><code>Object.keys</code></a> to simplify the job of iterating over the array:</p> <pre><code>// Assuming that db is an object as defined in the question. var next = function(db, key) { var keys = Object.keys(db) , i = keys.indexOf(key); return i !== -1 &amp;&amp; keys[i + 1] &amp;&amp; db[keys[i + 1]]; }; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload