0

Suppose there is an object in a JavaScript

let object = {
    "1": {"SUBJECT": "APPLE"},
    "2": {"SUBJECT": "BANANA"}
};

Which is equivalent to a dictionary in Python. Now if I wanted this: -

object2 = {
    "2": {"SUBJECT": "BANANA"},
    "1": {"SUBJECT": "APPLE"}
}

How do I get it?

VLAZ
  • 18,437
  • 8
  • 35
  • 54
  • 2
    Relevant https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – evolutionxbox Mar 24 '21 at 16:41
  • Does object properties have "order"? – Pipe Mar 24 '21 at 16:41
  • 1
    Does this answer your question? [How to turn an object with keys as indexes into an array in JavaScript?](https://stackoverflow.com/questions/36958870/how-to-turn-an-object-with-keys-as-indexes-into-an-array-in-javascript) – Thibault Walterspieler Mar 24 '21 at 16:41
  • @Pipe see the link from evolutionxbox - the short answer is "sort of yes" but it's also a bad idea to rely on it. – VLAZ Mar 24 '21 at 16:43
  • Not really @ThibaultWalterspieler I wanna reverse the entire object... Not just get the array... Thanks though – Broteen Das Mar 24 '21 at 16:57
  • I do have a sketchy approach though... Take the Keys in an array, Take the values in another array... Reverse both arrays and POOF! Join them... How does that sound? (I know... pretty naive) – Broteen Das Mar 24 '21 at 17:02
  • 2
    @BroteenDas that would do nothing. Object keys *that are integers* will be sorted first and will be in ascending order. You cannot override that. You either need a different data structure (a Map will always preserve insertion order) or keep a list of the keys in the array, sort that as you wish and then walk through the array fetching the corresponding value from the object. – VLAZ Mar 24 '21 at 17:11
  • Related: [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/q/30076219) – VLAZ Mar 24 '21 at 17:13
  • It doesn't work... It gets sorted back again... Idk how to prevent that... – Broteen Das Mar 24 '21 at 17:33
  • @BroteenDas "*It gets sorted back again*" -> "*Object keys that are integers will be sorted first and will be in ascending order. You cannot override that.*" – VLAZ Mar 24 '21 at 17:37
  • Hi, perhaps you could elaborate a bit on what 'reversing the order' of a JS object actually means and how the new structure (assuming it's possible to get it, which I suspect not) is to be used? There may be a better, more reliable way of getting what you want. – A Haworth Mar 24 '21 at 18:01

1 Answers1

0

So I figured it out... I just stored the Object.keys(object) in a list... reversed it and then iterated through the keys to get the object values... that was hella easy than I thought it would be... but thanks anyway to all of you who responded, interacted or even clicked on my question...

*sends love online*