On the backend form json:

$conditions = json_encode(array( '3' => array('three'), '2' => array('two'), '1' => array('one'), )); 

I save in the page element attribute:

 <div id="data" data-value="{"3":["three"],"2":["two"],"1":["one"]}"> 

The order of the elements of the array is preserved. But when I read this json in javascript, I get an object sorted by keys. Can this be somehow avoided or the only option is to change the keys of the source array in the order I need?

 <script> console.log(data.dataset.value); // Object { 1: Array[1], 2: Array[1], 3: Array[1] } </script> 
  • one
    Yes, either change the keys, which may also be wrong, because from the point of view of JS, you form an object, not an array. Or add a separate array (they are in json in square brackets) with the order of the keys ['3','2','1'] - Mike
  • @Mike and by the way, add the second array this thought. at least you don't have to go through the whole source, array_keys() and that's it. - toxxxa 5:57 pm

1 answer 1

The order of the elements of an associative array (dictionary) is not defined in JSON. Excerpt from RFC 4627

An object is an unordered collection of zero or more name / value pairs, where it is a string, a number, a boolean, a null, an object, or an array.

For this reason, the order you need to store yourself.

  1. You can save an array of keys in parallel in a specific order and use it for sorting.
  2. You can also add to the dictionary the key "weight" with a numerical value and sort by it.