Reputation: 153
I have a list as follows which has
[
%Photos{
url: "http://localhost:4000/test/img",
user: "localhost:4000/test/img/123"}]
How do I get the result as "localhost:4000/test/img/123"
which is a string?
Can anyone help me with this?
Thanks in advance.
Upvotes: 0
Views: 917
Reputation: 23101
Assuming your list was a single element list as you quoted, you could pattern match it directly with:
[%Photos{url: url}] = list
This will put the url into the url
variable. Example:
iex(2)> list = [%Photos{url: "http://localhost:4000/test/img", user: "localhost:4000/test/img/123"}]
[...]
iex(3)> [%Photos{url: url}] = list
[
%Photos{
url: "http://localhost:4000/test/img",
user: "localhost:4000/test/img/123"
}
]
iex(4)> url
"http://localhost:4000/test/img"
Upvotes: 3
Reputation: 121000
If the struct is under your control, you might implement Access
for it and use get_in/2
get_in(list, [Access.all(), :url]
Also, the comprehension and pattern matching work well.
for %Photos{url: url} <- list, do: url
The last, but not the least way would be Enum.map/2
list |> Enum.map(& &1.url)
All the above return all urls in the list. To get to the specific one, use Enum.at/3
and/or pattern matching.
Upvotes: 6