How to walk through a JavaScript object in sort order

Published: | Updated: | by Julian Knight Reading time ~1 min.
📖 Kb | 📎 Development | 🔖 JavaScript, ECMAscript

Using a JavaScript object like a keyed array, what is the simplest way to walk through the object?

Let’s say that we have an object like that shown in the example.

How do we output the content, ordered by key?

The code creates an array from the primary keys of the object, sorts the array and then walks through each entry.

Example Object 🔗︎

We can use this for reference

{
    "Pi3NR-LIVE": "Online",
    "Pi2NR-LIVE": "Online",
    "D1M04":"Online"
}

Code 🔗︎

const myObj = {
    "Pi3NR-LIVE": "Online",
    "Pi2NR-LIVE": "Online",
    "D1M04":"Online"
}

Object.keys(myObj).sort().forEach(function(key) {
    console.log( `${key} : ${myObj[key]}` )
})

/**
 * Will output (note the reordering):
 *
 * D1M04 : Online
 * Pi2NR-LIVE : Online
 * Pi3NR-LIVE : Online
 *
 **/

comments powered by Disqus