vendredi 7 avril 2017

Sort Nested Data Structure

Given a nested hash (see below) I would like to sort siblings which have a ':position' attribute.

In the hash below you can see the child and child_child attributes being an array but the position isn't ordered.

{:parent=>
      [{:id=>"29637484-4d39-4828-bebc-52e4ecb12250",
        :extra_data=>"parent_extra_data_1two",
        :position=>2,
        :resource_id=>"parent_resource_id_1two",
        :child=>
         [{:id=>"57c9dab3-f091-48e7-85a7-4a8a3c4782a6", :extra_data=>"child_extra_data_1two", :position=>2, :resource_id=>"child_resource_id_2two"},
          {:id=>"86b60506-f431-41f4-8555-30a83e9296f9",
           :extra_data=>"child_extra_data_1",
           :position=>1,
           :resource_id=>"child_resource_id_1",
           :child_child=>
            [{:id=>"04bb9af2-eac8-4fcf-8253-38b0ccb538c2", :extra_data=>"child_child_extra_data_one", :position=>1, :resource_id=>"child_child_one"},
             {:id=>"94947cc4-e27a-4f79-b585-f26db7ce4e66", :extra_data=>"child_child_extra_data_three", :position=>3, :resource_id=>"child_child_three"},
             {:id=>"98fe0b96-a8cd-488b-bf00-9d48633355d3", :extra_data=>"child_child_extra_data_two", :position=>2, :resource_id=>"child_child_two"}]}]}]}

Would become

{:parent=>
      [{:id=>"29637484-4d39-4828-bebc-52e4ecb12250",
        :extra_data=>"parent_extra_data_1two",
        :position=>2,
        :resource_id=>"parent_resource_id_1two",
        :child=>
         [{:id=>"86b60506-f431-41f4-8555-30a83e9296f9",
           :extra_data=>"child_extra_data_1",
           :position=>1,
           :resource_id=>"child_resource_id_1",
           :child_child=>
              [{:id=>"04bb9af2-eac8-4fcf-8253-38b0ccb538c2", :extra_data=>"child_child_extra_data_one", :position=>1, :resource_id=>"child_child_one"},
              {:id=>"98fe0b96-a8cd-488b-bf00-9d48633355d3", :extra_data=>"child_child_extra_data_two", :position=>2, :resource_id=>"child_child_two"},
              {:id=>"94947cc4-e27a-4f79-b585-f26db7ce4e66", :extra_data=>"child_child_extra_data_three", :position=>3, :resource_id=>"child_child_three"}]},
          {:id=>"57c9dab3-f091-48e7-85a7-4a8a3c4782a6", 
          :extra_data=>"child_extra_data_1two", 
          :position=>2, 
          :resource_id=>"child_resource_id_2two"
          }]}]}

Aucun commentaire:

Enregistrer un commentaire