2

I have a data.js file which contains an object like this:

var somedata = {
  "": "test",
  "51": "f",
  "123": "test1",
  "67": "test2",
  "hello": "ghr",
  ...
}

module.exports = somedata;

Unfortunately, this object gets reordered, and the order is quite important for the application. At this point, somebody suggested using Maps

thus, it became:

var somedata = new Map(Object.entries({
 "": "test",
 "51": "f",
 "123": "test1",
 "67": "test2",
 "hello": "ghr",
 ...
}))

module.exports = somedata;

ahh well, that didn't work either (or maybe I just didn't get maps). Hence, for the time being I built a workaround where I actually read the file using regex and put it into a map object to preserve object order. Unfortunately, as data.js is becoming quite big, this approach is quite time consuming. At which point I felt that I was looking at things the wrong way around.

My question: Is there a way to preserve object order somehow? Or at least a faster workaround than parsing the entire file?

see
  • 388
  • 4
  • 13
  • 1
    Objects do not guarantee ordering of keys. The only thing JS guarantees is that iterating over the keys is consistent but that does not imply the same order across every instance. Maps keep insertion order so at best you'd have to sort before adding to a map. But it sounds you probably don't want either but an ordered data structure to begin with so as you don't have to jump through hoops to get the ordering you need. – VLAZ Mar 16 '19 at 10:13

2 Answers2

2

You can use a map but not if your input is an object. Objects do not guarantee key order. You can instead use an array of pairs and construct a map out of them. Maps preserve insertion order:

const input = [
  [42, "Alice"],
  [30, "Bob"],
  [14, "Carol"],
  [39, "David"],
  [41, "Edel"],
  [2, "Fred"],
]

const map = new Map(input);

for(const [key, value] of map.entries()) {
  console.log(key, value)
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
1

There is not way, other than to use an array or other keeping order data structure at insertation time to preserve the order of the keys.

Object's keys are sorted by indices like values (positive 32 bit numbers as strings) first, then other strings in insertation order and then symbols.

A fast workaround is to take a dash in front of the number as key and access the object with it.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392