榆树中的可分类表

时间:2016-09-29 09:04:28

标签: elm

我正在尝试在Elm中设计一个功能,从Json解析数据,然后在可排序的表中呈现它。

当然,我正在使用解码器将Json数据存储在记录列表中;然后在视图中我将记录列表转换为Dicts列表,因为我想迭代网格中的数据。我还使用str列表列来为网格中的列提供标题,以确保数据在网格中出现的顺序是可自定义的。

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"
    ]

这就是问题:据我所知,不可能按键的值对列表进行排序,因此我必须对记录进行排序以获取值(例如,如果我想按名字排序)孩子们使用:

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

但是,列标题是字符串,它们并不总是与记录键相同(例如,对于字段,r.child.lastname,列标题是“姓氏”。)无论如何,我的理解是必须显式调用记录键,因此无法将列名称与记录键匹配。

我希望能够点击表格列并按字段排序; e.g:

我希望我写的很清楚。谢谢你的帮助!

1 个答案:

答案 0 :(得分:5)

如何将columnsData保持为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