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?

11
  • 2
    Relevant stackoverflow.com/questions/5525795/… Commented Mar 24, 2021 at 16:41
  • Does object properties have "order"? Commented Mar 24, 2021 at 16:41
  • 1
    Does this answer your question? How to turn an object with keys as indexes into an array in JavaScript? Commented Mar 24, 2021 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. Commented Mar 24, 2021 at 16:43
  • 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. Commented Mar 24, 2021 at 17:11

1 Answer 1

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*

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.