Error editing form with dynamic drop-down list - Cakephp

Friends, in my registration form for a new product at the bank, I have the categories and subcategories fields. The subcategory value is only populated after choosing a parent category. This works perfectly, however when I want to edit the product, the subcategory value does not carry the bank value. It comes empty. I would like to bring the same! My code looks like this:

<?php
$categories_list = [];
$subcategorias_list = [];

   foreach ($categories as $category) {
   $categories_list[$category->id] = $category->name;

   foreach ($category->subcategories as $subcategory) {
   $subcategories_list[$category->id][$subcategory->id] = $subcategory->name;
    }
   }
?>

   <small>Select Category</small>
   <?= $this->Form->control('category_id', [
            'class' => 'form-control form-control-user',
             'id' => 'category',
             'label' => false,
             'required' => true,
             'options' => $categories_list,
             'placeholder' => 'Category',
                                           ]); 
?>

<small>Select Subcategory</small>
<?= $this->Form->control('subcategory_id', 
[
            'class' => 'form-control form-control-user',
            'id' => 'subcategory',
            'label' => false,
            'required' => true,
            'options' => $subcategories_list,
            'placeholder' => 'SubCategory',
            ]); 
?>

My js looks like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <script>
    var subCategories = <?= json_encode($subcategorias_list); ?>;

    $(document).ready(function() {
        $('#category').change(function() {

            var categoryId = $(this).val();

            var subCategoriesObject = subCategories[categoryId];

            $('#subcategory option:gt(0)').remove();
            var subCategoriesSelect = $('#subcategory');

            $.each(subCategoriesObject, function(key, value) {
                subCategoriesSelect.append($("<option></option>").attr("value", key).text(
                    value));
            });

        });
    });
    </script>

I appreciate any comments and if anyone can give an idea to bring the value in the edit form.