Knitting sorting table

I am trying to create a function in Elm that parses data from Json and then displays it in a sortable table.

Naturally, I use a decoder to store Json data in a list of records; then in the view, I convert the list of records into a list of Dicts, because I would like to iterate over the data in the grid. I also use str list columns to give headings to columns in the grid to ensure that the order in which data is displayed in the grid is customizable.

resourceDecoder : Decoder Resource
resourceDecoder =
    decode Resource
        |> required "year" int
        |> required "total_amount" string
        |> required "seq_type" string
        |> required "sent" bool
        |> required "parents_id" int
        |> required "month" int
        |> required "location_id" int
        |> required "child" childDecoder
        |> required "id" int
childDecoder : Decoder Child
childDecoder =
    decode Child
        |> required "firstname" string
        |> required "lastname" string
responseDecoder : Decoder (List Resource)
responseDecoder =
    Json.Decode.list resourceDecoder
recordToDict : Resource -> ResourceDict
        recordToDict record =
            Dict.fromList
                [ ( "Year", toString record.year )
                , ( "Total Amount", record.total_amount )
                , ( "Sequence Type", record.seq_type )
                , ( "Sent", toString record.sent )
                , ( "Parents", toString record.parents_id )
                , ( "Month", toString record.month )
                , ( "Location", toString record.location_id )
                , ( "Firstname", record.child.firstname )
                , ( "Lastname", record.child.lastname )
                , ( "id", toString record.id )
                ]
columnsData : List String
columnsData =
    [ "Firstname"
    , "Lastname"
    , "Year"
    , "Total Amount"
    , "Sequence Type"
    , "Sent"
    , "Parents"
    , "Month"
    , "Location"
    ]

Here's the problem: as far as I know, it was not possible to sort the list of dicts by values ​​for the key, so I need to sort the record for the value (for example, if I want to sort by first name, the children use:

List.sortBy (\r -> r.child.lastname) grid.resources

, (, , r.child.lastname, - "".) , , .

; :

, . !

+4
1

Data Dict of ? Dict?

( Key, , String )

type alias Key = String
columnsData : Dict.Dict String Key
columnsData = Dict.fromList
    [ ("Firstname",     "firstName")
    , ("Lastname",      "lastName")
    , ("Year",          "year")
    , ("Total Amount",  "totalAmount")
    , ("Sequence Type", "seqType")
    , ("Sent",          "sent")
    , ("Parents",       "parents")
    , ("Month",         "month")
    , ("Location",      "location")
    ]

sort : Key -> List ResourceDict -> List ResourceDict
sort key dicts =
  let
    getVal dict = Maybe.withDefault "-" <| Dict.get key dict
  in List.sortBy getVal dicts
+5

Source: https://habr.com/ru/post/1656192/


All Articles