Hi. new to elixir. I need to remove a struct or update it from given array of structs
array = [%{id: "1", img: "2", tokens: "3"}, %{id: "2", img: "2", tokens: "3"},
%{id: "3", img: "2", tokens: "3"}]
Thanks in advance
Hi. new to elixir. I need to remove a struct or update it from given array of structs
array = [%{id: "1", img: "2", tokens: "3"}, %{id: "2", img: "2", tokens: "3"},
%{id: "3", img: "2", tokens: "3"}]
Thanks in advance
Hey @newbie1 welcome!
Can you sketch what kind of change you need to make, and how you’re going to identify each struct? Do you need to update a specific one by ID?
Also as a minor note you can format the code by doing ``` before and after the text. I’ve edited your post by way of example.
@benwilson512 what i want is remove %{id: “1”, img: “2”, tokens: “3”} from array so it would look like
array = [%{id: "2", img: "2", tokens: "3"}, %{id: "3", img: "2", tokens: "3"}]
or update it like %{id: “1”, img: “4”, tokens: “4”} so my array would look like
%{id: "3", img: "2", tokens: "3"}]```
Sure! In your case you’ve got a couple options. It’s the first item in the list so one option is to just take the tail of the list:
list = tl(list)
If you want to remove any maps with id: 1
regardless of where they are in the list you can just filter them out:
list = Enum.reject(list, fn item -> item.id == "1" end)
If you talk a bit about what you’re using this list for we can also recommend some other data structures that may be more relevant. For example if you’re mostly focused on just having a set of structs and referring to them by ID a map may be more useful:
map = %{
"2" => %{id: "2", img: "2", tokens: "3"},
"3" => %{id: "3", img: "2", tokens: "3"},
}
This would let you do Map.delete(map, "2")
@benwilson512 second option did the trick. Thank you
To add to @benwilson512’s answer: There are a couple of libraries that abstract the map syntax away from you, like the arrays package I maintain.