6

I have a array:

arr = [ ['1', 'a'], ['12', 'b'], ['2', 'c'] ];

I'm using Object.fromEntries() to convert the array into objects with key/value pair. But the problem is Object.fromEntries() seems to changing the sequence of my array based on the key, eg: I want my above array to be converted into object with the same sequnce as shown in the code:

expected o/p:

{1: 'a', 12: 'b', 2: 'c'}

Actual o/p from the fromEntires()

{1: 'a', 2: 'c', 12: 'b'}

any idea why does the function do that and if there is a way to avoid this and render the same sequcne as provided in the array?

asked Apr 12, 2022 at 21:14
6
  • 6
    Those two objects are semantically equivalent. Javascript objects do not have an actual order for properties; it's often respected in simple situation, but you should not count on that. Commented Apr 12, 2022 at 21:16
  • 3
    If you want your object to be ordered, try using a Map Commented Apr 12, 2022 at 21:20
  • 1
    @Aioros JavaScript object do have an order (at least when using any reasonably up-to-date browser). It's just that the number-like keys come first and in ascending order. Commented Apr 12, 2022 at 21:24
  • @Ivar is this just chrome related? Commented Apr 12, 2022 at 21:25
  • 3
    @EugenSunic: No, it’s part of the language specification. Commented Apr 12, 2022 at 21:30

1 Answer 1

5

The order of properties in JavaScript objects is not guaranteed to be the insertion order. In particular, keys that parse as integers (such as in your case) will not respect insertion order.

If you need to guarantee order, try using a Map instead:

let arr = [ ['1', 'a'], ['12', 'b'], ['2', 'c'] ];
const map = new Map();
for(let value of arr){
 map.set(value[0], value[1])
}
answered Apr 12, 2022 at 21:25
4
  • 3
    It’s not only "some browsers". Number-like keys are always sorted numerically first, as per specification: tc39.es/ecma262/#sec-ordinaryownpropertykeys Commented Apr 12, 2022 at 22:19
  • @Lauren: thank you but my problem remains as is- even if I use Map, I want my final o/p to be in object format and for that we need to use Object.fromEntires() ultimately right? and again the o/p changes the sequnce. is my understanding right? Commented Apr 12, 2022 at 22:24
  • 1
    @user1234 Unfortunately, if you want your final result to be in a specific order, you cannot use an object with number-like keys. If you want to use an object with number-like keys, you cannot have it in a specific order. Commented Apr 12, 2022 at 22:31
  • 1
    @user1234 If a Map is not a good fit, another option would be to use an array, where you store the value at a particular index...e.g. arr[1] = a, arr[2] = c ... arr[12] = b Commented Apr 12, 2022 at 22:32

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.