0

I receive data from a REST API, which contains id and name properties ordered by name. The data is:

Array [
  Array [
    960,
    "",
  ],
  Array [
    588,
    "         Computer Associate System, LLC",
  ],
  Array [
    481,
    "1111",
  ],
  Array [
    91,
    "123Inkjets",
  ],
  Array [
    73,
    "1and1 Internet",
  ],
]

Then, I want to create an object that still ordered by name:

const vendors = {};
const data = response.data.DATA;
if (data !== undefined) {
   for (let index = 0; index < data.length; ++index) {
      const value = data[index];
      vendors[value[0]] = value[1];
   }
}

However, the result of vendors is not ordered by the name. How can I order it? I still need to return vendors as an object with "id" : "name"

Thanks

fubar
  • 16,918
  • 4
  • 37
  • 43
myTest532 myTest532
  • 2,091
  • 3
  • 35
  • 78
  • 1
    There are existing questions, relevant to this. Including: https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties – Ben Aston Feb 13 '20 at 22:03
  • Nope. That question is ordering by key, not value – myTest532 myTest532 Feb 13 '20 at 22:07
  • 1
    Whilst you want to order by value, that is still akin to you ordering the keys based on their value. – fubar Feb 13 '20 at 22:09
  • 1
    @myTest532myTest532 As I understand it, object properties in JavaScript are not reliably ordered in the way you might want them to be. Arrays, Sets and Maps are ordered data structures, however. – Ben Aston Feb 13 '20 at 22:15
  • 1
    Objects are not ordered. If order is important to you, keep them as an array. – Bergi Feb 13 '20 at 22:41
  • Why the object is not keeping the array order? It's coming already ordered from the database (data variable) – myTest532 myTest532 Feb 13 '20 at 22:53
  • ES2015 guarantees that non-integer keys are ordered in insertion order [(see here)](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). However, you are making the keys as the ID - those are integer keys. They will be ordered in ascending order automatically. If you need to preserve the order, keep them in an array, just map the inner arrays to objects (this sounds like what you need anyway). – Klaycon Feb 13 '20 at 23:03
  • @Klaycon yes, it is what I need. Could you please show me an example? – myTest532 myTest532 Feb 13 '20 at 23:10
  • @myTest532myTest532 can you show how the `vendors` object will be used? – Klaycon Feb 13 '20 at 23:13
  • @Klaycon I need the vendors object with "id" : "value". It will be used in a react native Picker component – myTest532 myTest532 Feb 14 '20 at 15:15

0 Answers0