javascript – Why does my array sort order changes when I pass it to JS using WP_REST_Response?


I am passing the posts result of a query to JS so it can render the data in a select. Before I send out the result like this:

return new WP_REST_Response( $return_data, 200 );

I checked the array in PHP an it yields the following, which is fine (sorted by name)

array(8) {
  string(3) "Gus"
  string(3) "Mia"
  string(4) "Odin"
  string(5) "Pablo"
  string(8) "Salvator"
  string(6) "Scooby"
  string(5) "Snowy"
  string(6) "Wesley"

In my JS, I have the following code:

this.request = $.ajax({
  url: `${homeURL}/wp-json/mdr/v1/${animalType}`,
  type: 'get',
  dataType: 'json',
  success: function (result) {

Which prints the following:

Object {
  1479: "Odin",
  1485: "Wesley",
  1488: "Pablo",
  1489: "Gus",
  1490: "Salvator",
  1491: "Scooby",
  1492: "Snowy",
  1499: "Mia"

Why is the array converted to an object sorted by the ID instead of the order that I passed it from PHP?

in progress 0
csaborio 6 months 2021-06-06T20:35:46-05:00 0 Answer 0 views 0

Answer ( 1 )


    Fix by using:

    return new \WP_REST_Response( \json_encode( $return_data), 200 );

Leave an answer