javascript object always being created in ascending order

3

I'm dealing with similar code in a project:

var groupedObject = {};
groupedObject['2016'] = {};
groupedObject['2022'] = {};
groupedObject['2014'] = {};
groupedObject['2021'] = {};
console.log(groupedObject);

No matter the order in which object values are created, the ALWAYS log returns the object in ascending order

Output:

2014:{}
2016:{}
2021:{}
2022:{}

I do not want this behavior. Could anyone explain why? How do I return the object in the order it is being created?

    
asked by anonymous 07.03.2018 / 19:23

3 answers

2

When the keys names are purely numeric, they are automatically arranged in ascending order, no matter what order you entered them. If they are not numeric, the order will be kept according to the order entered.

  

I could not understand the importance of this order, since it does not matter   of "2016" is before "2014" if when you want to access a   by the name, it will be there (?).

But if you really want to sort by the insertion order, I suggest adding at least 1 letter to the keys names. I think this would not hurt your application at all.

It would be something like:

var groupedObject = {};
groupedObject['n2016'] = {};
groupedObject['n2022'] = {};
groupedObject['n2014'] = {};
groupedObject['n2021'] = {};
console.log(groupedObject);

Or you could use an underscore :

var groupedObject = {};
groupedObject['2016_'] = {};
groupedObject['2022_'] = {};
groupedObject['2014_'] = {};
groupedObject['2021_'] = {};
console.log(groupedObject);
    
07.03.2018 / 23:09
3

The insertion order in the object is not guaranteed by the specification.

However, if you use Map this is already truth. This provides you with the same functionality ensuring the insertion order, but the syntax will already be different.

Creation becomes:

var groupedObject = new Map();

To assign a value to a key, you must use the set method by passing the key and value:

groupedObject.set('2016', {});

To get the value of a key you must use get indicating the name of the key:

let valor = groupedObject.get('2016')

Going through all elements is done with for ... of :

for (let obj of groupedObject){
    //fazer algo com obj
}

See your example in Map :

var groupedObject = new Map();
groupedObject.set('2016', {});
groupedObject.set('2022', {});
groupedObject.set('2014', {});
groupedObject.set('2021', {});

for (let obj of groupedObject){
  console.log(obj);
}

console.log(groupedObject.get('2016'));
    
07.03.2018 / 20:52
1

The problem is not in the console.log but in the JS object that by default does not keep the order, I found an alternative in the SOen that can help get you to the result you want.

var groupedObject = {};
groupedObject[' ' +2016] = {};
groupedObject[' ' +2022] = {};
groupedObject[' ' +2014] = {};
groupedObject[' ' +2021] = {};
console.log(groupedObject);

ref: How to prevent automatic sort of Object numeric property ?

    
07.03.2018 / 20:52