1

I have an object:

var myObj = {
    "0": "#fff",
    "trace": "#0000cc",
    "0.1": "#3366ff",
    "0.2": "#999900",
    "0.5": "#ffcc00",
    "1": "#ff9900",
    "2": "#ff0000",
    "5": "#ff00ff",
    "10": "#ccffff"
        }

I need to call this object keys and create list of items with their key text on each of them:

var myKeys = Object.keys(myObj);

myKeys.forEach(function (item) {

   var li = document.createElement("li");

   li.appendChild(document.createTextNode(item));

});

This returns:

<li>0</li><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>10</li><li>trace</li><li>0.1</li><li>0.2</li><li>0.5</li>

How can I make this in a way that it doesn't automatically sort the object?

Nicolas T
  • 293
  • 1
  • 4
  • 13
  • 3
    There is no order in objects, it can't be sorted, or randomized, or whatever the issue is. The keys however, is an array, and you can just sort that however you like. – adeneo Feb 10 '16 at 19:43
  • If you want to guarantee the order you should use an array. – jasonwarford Feb 10 '16 at 19:46
  • Using the `forEach` or `for in` mechanism in JavaScript does not guarantee order, and it seems to be going in lexicographical order here. – Travis J Feb 10 '16 at 19:48
  • You might be interested in https://github.com/loverajoel/jstips/blob/gh-pages/_posts/en/2016-02-01-map-to-the-rescue-adding-order-to-object-properties.md – neilsimp1 Feb 10 '16 at 20:09

1 Answers1

2

Objects aren't explicitly sorted. Many engines will implicitly sort the keys when using Object.keys but this isn't a guarantee. If you want the keys in a particular order, you'll have to sort them yourself after retrieving them.

Mike Cluck
  • 28,921
  • 12
  • 72
  • 85