How to prevent drupalSettings to sort settings object I attach drupalSettings in a preprocess hook using code similar to the following one. 

$settings = [
  'bcd' =&gt; 'BCD',
  'abc' =&gt; 'ABC'
];

$variables['#attached']['drupalSettings']['options'] = $settings;


When I print the content of drupalSettings using console.log(drupalSettings.options); I  get a sorted object.

{ 'abc' : 'ABC','abc' : 'BCD'}


Is this the normal behavior? How can I prevent it?
It's not Drupal that sorts the drupalSettings array, but it's console.log() that sorts the properties of drupalSettings.options before outputting it. See Show original order of object properties in console.log where the answer explains this.

If you really want to avoid console.log() sorts the object properties, you could call console.log() using code similar to the following one.

console.log(JSON.stringify(obj, drupalSettings.options, null, 2));


I would rather use this code if it's really important to see the object properties in the order they are set.