2016-09-29 70 views
4

我试图在Elm中设计一个功能,它解析来自Json的数据,然后将其呈现在可排序的表中。Elm中的可排序表

当然,我使用解码器将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" 
    ] 

这里的问题:据我所知,这是不可能的排序的键值类型的字典列表,所以我必须要记录entires排序为一个值(例如,如果我想按照儿童的名字排序使用:

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

但是,列标题是字符串,它们并不总是与记录键相同(例如,字段r.child.lastname,列标题是'姓')。无论如何,我的理解是记录键必须显式调用,所以不能将列名与记录键匹配。

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

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

+0

这将是超爽的您提供输入和期望的输出 – halfzebra

+1

对不起,我不知道到底你在这方面的输入和输出是什么意思,但我已经包含了一个图像。 –

+2

您是否考虑过使用https://github.com/evancz/elm-sortable-table - 据我所知 - 能够提供您想要的功能? –

回答

5

如何将columnsData保存为 字典的键和标题? 然后使用该键排序字典的列表?

(我定义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 
+0

这个伎俩!事实上,由于资源已经是字典,我不必使字段成为字典,而只是列出字符串。但是你建议的排序功能正是我所期待的。 –