0

If I have an object like this:

const database = {
    921: "some value",
    342: "another value",
    999: "etc",
    432: "and etc"
};

then how do I loop over it in the order it's in now? I'm using a "for .. in" loop currently but it iterates over the objects in numerical order instead of the order they're declared. Googling turned up nothing.

Thanks in advance.

Coleman
  • 11
  • 1
  • 3
  • Positive integer values will be sorted in ascending order. There is nothing you can do about it. In general, it's bad practice to expect specific order for object keys, even if [in some cases that would work](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties). There are many operations that can unintentionally disturb the order you expect. You should utilise a different structure - either an array, or at the very least a map, which does preserve the order of insertion. – VLAZ Oct 22 '20 at 11:36
  • Instead of using an object literal, use `Map` object. It will ensure the order of the keys. – Yousaf Oct 22 '20 at 11:37
  • Related: https://stackoverflow.com/questions/63327922/javascript-object-storage-order – Yousaf Oct 22 '20 at 11:50

0 Answers0