'Multidimensional array pass to Ajax Sortable jQuery

I use sortable jQuery ui function. With this

 $(".draggable-right").sortable({
            connectWith: ".connected-sortable",
    

            update: function(event, ui) {
                var ordine_video = $(this).sortable('toArray', {
                    attribute: 'data-id'
                });


                // POST to server using $.post or $.ajax
                $.ajax({
                    data: {
                        'ordine_video': ordine_video,
                    },
                    type: 'post',
                    dataType: 'json',
                    url: 'save_playlist.php'
                });
                //     alert(idsInOrder);
                console.log(ordine_video);

            },


        }).disableSelection();

I can pass an array with attribute:data-id values in arrays as

["BMPR-00026.mp4", "BMPR-00026.mp4"]

If I want to pass an array like this with key and value

{"BMPR-00026.mp4":"value_1", "BMPR-00026.mp4": "value_2"}

how can do? I have the field in

<li class="ui-sortable-handle" data-id="BMPR-00026.mp4" style="" rel="value_1">element</li>
<li class="ui-sortable-handle" data-id="BMPR-00026.mp4" style="" rel="value_2">element</li>


Solution 1:[1]

Consider the following.

function serializeList(list) {
  var results = {};
  $("li", list).each(function(i, el) {
    results[$(el).attr("data-id")] = $(el).attr("rel");
  });
  return results;
}

$(".draggable-right").sortable({
  connectWith: ".connected-sortable",
  update: function(event, ui) {
    var ordine_video = serializeList(this);
    $.ajax({
      data: {
        'ordine_video': ordine_video,
      },
      type: 'post',
      dataType: 'json',
      url: 'save_playlist.php'
    });
    console.log(ordine_video);
  }
}).disableSelection();

This creates a Function, that you can pass a List to and it will iterate each List Item to build an Object.

There is a caveat, each data-id must be unique. Like so:

{
  "BMPR-00026.mp4": "value_1",
  "BMPR-00027.mp4": "value_2"
}

If they are the same, the value of that Index will be updated instead of adding a new entry.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Twisty