I attach drupalSettings in a preprocess hook using code similar to the following one.

$settings = [
  'bcd' => 'BCD',
  'abc' => '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?

  • 1
    I don't check code, but i have a tip for you. Using json encode on php convert to string and using json parse on js to convert to object.
    – MrD
    Oct 26, 2019 at 7:01

1 Answer 1


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.

  • Thanks @Kiamlaluno it's right, not Drupal that sort the drupalSettings.
    – berramou
    Oct 27, 2019 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.