1

I want to loop to do something like this

const firstColumn = {};

for (let index = 1; index < 20; index++) {
    firstColumn[index] = {}
}

I want to end with something like this

const data = {
    "1": {},
    "2": {},
    "3": {},
    // So on
}

But I'm getting this console output.

    Object {
  "1": Object {},
  "10": Object {},
  "11": Object {},
  "12": Object {},
  "13": Object {},
  "14": Object {},
  "15": Object {},
  "16": Object {},
  "17": Object {},
  "18": Object {},
  "19": Object {},
  "2": Object {},
  "3": Object {},
  "4": Object {},
  "5": Object {},
  "6": Object {},
  "7": Object {},
  "8": Object {},
  "9": Object {},
}

the Funny thing if I limit the loop iteration to less than 10 I get the right sequence.

for (let index = 1; index < 10; index++) {
    firstColumn[index] = {}
}

// output

Object {
"1": Object {},
  "2": Object {},
  "3": Object {},
  "4": Object {},
  "5": Object {},
  "6": Object {},
  "7": Object {},
  "8": Object {},
  "9": Object {},
}

I honestly don't get it. Maybe somebody smarter than me can help me. Thanks in advance.

Millenial2020
  • 2,465
  • 9
  • 38
  • 83
  • 4
    Why do you need the keys sorted? See https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key – Umair Sarfraz Apr 27 '20 at 20:45
  • 4
    An array of objects may be better in this case, instead of an object with sequential keys of more objects. – Sean Apr 27 '20 at 20:47
  • Yeah but I have a third part module that thanks those that format for some odd reason. If it was an array it would have being pretty straight forward. – Millenial2020 Apr 27 '20 at 20:48
  • Because keys are STRINGS, not numbers. Not all JS engines honor order by how they were entered. – epascarello Apr 27 '20 at 20:49
  • @epascarello and according to the spec, string keys are ordered by insertion time, not lexically. – Jonas Wilms Apr 27 '20 at 20:51
  • 3
    What a nutty requirement for that 3rd party module. Fork it and change it to something sane. – sdotson Apr 27 '20 at 20:51
  • @JonasWilms yes, but not all engines work that way, hence why people always have said not to rely on order of an object. – epascarello Apr 27 '20 at 20:52
  • Where are you printing that output? You are seeing the ordering your engine / console chose to represent objects. Object key-value pairs are not sorted, as long as you don't iterate over them with a `for..in` et al. – Jonas Wilms Apr 27 '20 at 20:53
  • The console is free to output object properties in any order it choses to use. – trincot Apr 27 '20 at 20:56
  • The output its just a console.log(firstColumn) at the end of the code – Millenial2020 Apr 27 '20 at 20:56
  • Also, the order that the console uses is no guarantee at all of what a third party API will determine as the order. – trincot Apr 27 '20 at 20:57

0 Answers0