BoumTAC
BoumTAC

Reputation: 3771

How to update one element of a list

I have an update function that take a postID and a title to update my post.

I want to loop over my posts to find the post and update its value. I tried using List.map but I don't know where to put here. Here is what I want in pseudo code:

update action model =
  case action of
    UpdateTitle postID title ->
      //something like this:
      for post in model.posts :
        if post.id == postID then
          { post | title = title }

      ( model.posts , Effects.none )

Upvotes: 3

Views: 602

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

You can use List.map, passing in a mapping function that only updates the post with a matching ID.

update action model =
  case action of
    UpdateTitle postID title ->
      ( List.map (setTitleAtID title postID) model.posts , Effects.none )

setTitleAtID title postID post =
  if post.id == postID then
    { post | title = title }
  else
    post

Upvotes: 6

Related Questions