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?
1 Answer 1
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])
}
-
3It’s not only "some browsers". Number-like keys are always sorted numerically first, as per specification: tc39.es/ecma262/#sec-ordinaryownpropertykeysTerry– Terry2022年04月12日 22:19:20 +00:00Commented 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?user1234– user12342022年04月12日 22:24:38 +00:00Commented 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.Lauren Prete– Lauren Prete2022年04月12日 22:31:01 +00:00Commented 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] = bLauren Prete– Lauren Prete2022年04月12日 22:32:03 +00:00Commented Apr 12, 2022 at 22:32
Map