doormitor
Find and upsert struct in an array of structs
Hello.
I have a following scenario 1: an array of structs (Post) that within themselves contain another array with struct (Like).
[
Post%{
id: 1,
likes: [
Like%{id: 1, post_id: 1, type: "upvote"},
Like%{id: 2, post_id: 1, type: "downvote"},
]
},
Post%{
id: 2,
likes: [
Like%{id: 3, post_id: 2, type: "downvote"},
]
}
]
Now, I get the request to update the like on the post, like this:
Like%{id: 3, post_id: 2, type: "upvote"},
This means that I need to find the post that has id of 2, then in the array find the struct that has id of 3 and post_id of 2, and change the type to “upvote”, such that produces the following result:
[
Post%{
id: 1,
likes: [
Like%{id: 1, post_id: 1, type: "upvote"},
Like%{id: 2, post_id: 1, type: "downvote"},
]
},
Post%{
id: 2,
likes: [
Like%{id: 3, post_id: 2, type: "upvote"}, <- this changed
]
}
]
Scenario 2:
This scenario is basically the same as the above with one additional request. Lets get another Like struct like this:
Like%{id: 4, post_id: 2, type: "upvote"},
Its the same routine: find the post with the id of 2, but because we dont have a like struct with id of 4, we need to insert the whole Like struct in the array, like this:
[
Post%{
id: 1,
likes: [
Like%{id: 1, post_id: 1, type: "upvote"},
Like%{id: 2, post_id: 1, type: "downvote"},
]
},
Post%{
id: 2,
likes: [
Like%{id: 3, post_id: 2, type: "upvote"},
Like%{id: 4, post_id: 2, type: "upvote"} <- This is new
]
}
]
Can someone help me with this?
Marked As Solved
joey_the_snake
I had some sloppy mistakes in there. This is a cleaned up version that should compile:
%{id: new_like_id, post_id: new_like_post_id} = new_like
posts
|> Enum.map(fn
%{id: ^new_like_post_id} = post ->
{likes, found} =
Enum.map_reduce(post.likes, false, fn
%{id: ^new_like_id} = like, _found -> {%{like | type: new_like.type}, true}
like, found -> {like, found}
end)
likes = if found, do: likes, else: [new_like | likes]
%{post | likes: likes}
post ->
post
end)
The mistakes:
- get rid of the first
album -> - You can’t pin the ids the way I did so you can assign them to variables using pattern matching
Also Liked
doormitor
Yes that worked! Now I will put effort to study those lines. Thank you!
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









