Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to sort a Javascript object, or convert it to an array?
    text
    copied!<p>I have some JSON data that I get from a server. In my JavaScript, I want to do some sorting on it. I think the sort() function will do what I want.</p> <p>However, it seems that JavaScript is converting the JSON data into an Object immediately on arrival. If I try to use the sort() method, I get errors a-plenty (using Firebug for testing).</p> <p>I've looked around the net, and everyone seems to say that for one thing, JSON objects are already JavaScript arrays, and also that Objects can be treated just like arrays. Like over on <a href="https://stackoverflow.com/questions/752222/jquery-with-json-array-convert-to-javascript-array">this question</a>, where in one of the answers, a guy says "The [Object object] is your data -- you can access it as you would an array."</p> <p>However, that is not exactly true. JavaScript won't let me use sort() on my object. And since the default assumption is that they're all the same thing, there don't seem to be any instructions anywhere on how to convert an Object to an Array, or force JavaScript to treat it as one, or anything like that.</p> <p>So... how do I get JavaScript to let me treat this data as an array and sort() it?</p> <p>Console log output of my object looks like this (I want to be able to sort by the values in the "level"):</p> <p>OBJECT JSONdata</p> <pre><code>{ 1: { displayName: "Dude1", email: "dude1@example.com&lt;mailto:dude1@example.com&gt;", lastActive: 1296980700, level: 57, timeout: 12969932837 }, 2: { displayName: "Dude2", email: "dude2@example.com&lt;mailto:dude2@example.com&gt;", lastActive: 1296983456, level: 28, timeout: 12969937382 }, 3: { displayName: "Dude3", email: "dude3@example.com&lt;mailto:dude3@example.com&gt;", lastActive: 1296980749, level: 99, timeout: 129699323459 } } </code></pre>
 

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