0

I encountered a problem that the object I created is sorting the keys in alphabetical order. This sorting happens only in my React Native project not when I run usual js file or browser console.

let obj = {
    b:1,
    a:2
}
console.log(obj) // {"a": 2, "b": 1}

I tried using Map() and then converted to Object but still keys are sorting itself. What is the reason behind it and how to fix it?

Version: react-native-cli: 2.0.1 react-native: 0.66.2 node: v16.13.0

UHS
  • 584
  • 4
  • 8
  • Objects are not meant to store data in sequentially, If you want to store data sequentially then you should use Array or Map. Both preserve the order of insertion – DecPK Dec 14 '21 at 16:09
  • But it is sorting the keys in my project only not in a normal js file or browser console it's not random and I wanted to know that why it is happening and how to prevent it – UHS Dec 14 '21 at 16:12
  • *"I tried using Map() and then converted to Object"* why? was there an issue with the Map? A Map would guarantee the order. – Thomas Dec 14 '21 at 16:13
  • See https://stackoverflow.com/a/57701452/476… – deceze Dec 14 '21 at 16:14
  • I don't know react-native, but i don't see it altering node's behavior much (if at all), and i can't reproduce the described `console.log` behavior on node. – ASDFGerte Dec 14 '21 at 16:17

0 Answers0