Nan Li
Nan Li

Reputation: 593

In Elm, how to access a field by string?

in JavaScript we can do obj['name'], is there something similar in Elm?

What I'm trying to do is to create a function to sort a list when user clicks on the column header, so my sort function will take a string or a (.) function to indicate which field to sort by. How do I achieve this?

Upvotes: 2

Views: 386

Answers (1)

daniula
daniula

Reputation: 7028

You can't use string to access record field because Elm compiler won't be able to find out if your code is correct. You should create your own function which will map your column name to possible field names and then use it with core List.sortBy:

type alias User = { name : String, height: Int }

sort : String -> List User -> List User
sort column rows = 
    case column of
        "name" -> List.sortBy .name rows
        "height" -> List.sortBy .height rows
        _ -> rows

Upvotes: 3

Related Questions