Skip to content
Advertisement

Order object properties based on values of an array

I have the following object:

JavaScript

And the following array:

JavaScript

However I would like to arrange the properties in the object based in the value of the array, so the result would be:

JavaScript

How can I achieve this? I couldn’t find anything on google related to this, only how to sort an array of objects.

Advertisement

Answer

Object properties can’t be reordered like array keys. You will have to create a new blank object (assuming stdClass objects), and then add in the properties in the desired order. First, let’s recreate the source object:

JavaScript

Then, here’s your new order:

JavaScript

Then, we create a new object and add the properties in the desired order:

JavaScript

This results in:

JavaScript

If you need to do this often, turn the operation into a helper function:

JavaScript

Another approach would be to create an associative array with the keys in the desired order, and then cast it into a stdClass object (as we did in instantiating your source object). You could also use the above function/logic for reordering array keys with very minor modifications.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement