Monday 31 January 2022

Can I preserve the order of a javascript object's entries, when some entry keys are integers?

I am working with an object where I need to preserve the order of the entries, even though some keys are alphanumeric and others are integers. (Yes, I know.)

The object I'm starting with looks like this:

{
  a: 'the',
  quick: 'quick',
  b: 'brown',
  fox: 'fox'
}

After manipulation, the object should look like this:

{
  a: 'the',
  0: 'quick',
  b: 'brown',
  1: 'fox'
}

But. Because iteration order in javascript objects differs from insertion order (integers are iterated first), if I go about this straightforwardly, I won't get the correctly ordered result:

let myReindexedObject = {};

myReindexedObject['a'] = 'the';
myReindexedObject['0'] = 'quick';
myReindexedObject['b'] = 'brown';
myReindexedObject['1'] = 'fox';

console.log(myReindexedObject);

I've tried to solve this issue by building a Map (which, unlike an object, preserves entry order) which I can then convert into an object.

Source: (I adapted this gist by Luke Horvat: Convert ES6 Map to Object Literal .)

Can you guess what happens?

let myMap = new Map();

myMap.set('a', 'the');
myMap.set('0', 'quick');
myMap.set('b', 'brown');
myMap.set('1', 'fox');

let myArray = Array.from(myMap);

let myReindexedObject = myArray.reduce((myReindexingObject, [key, value]) => {
  return Object.assign(myReindexingObject, { [key]: value })
}, {});

console.log(myReindexedObject);

Is there any way I can use integer-based keys like 0 and 1 and still preserve the object entries in a custom order?

Or do I need to consider other approaches?



from Can I preserve the order of a javascript object's entries, when some entry keys are integers?

No comments:

Post a Comment