Blog
Blog
Accessing deeply nested values in Elixir
The Access module in Elixir is a handy tool for working with nested data structures like lists and maps. Here are a few examples demonstrating different ways to access deeply nested values using the Access module.
- Name
- Matt
- @mplatts
1 year ago
Use get_in/2
to access nested values:
data = %{
a: %{
b: %{
c: 42
}
}
}
value = get_in(data, [:a, :b, :c])
IO.inspect(value) #=> 42
# Doesn't crash when the keys don't exist
value = get_in(data, [:x, :y, :z])
IO.inspect(value) #=> nil
Access items in a list:
data = %{
users: [
%{
id: 1,
name: "Alice",
friends: [
%{id: 2, name: "Bob"},
%{id: 3, name: "Charlie"}
]
}
]
}
# Get the name of the first friend of the first user
name = get_in(data, [:users, Access.at(0), :friends, Access.at(0), :name])
IO.inspect(name) #=> "Bob"
Get a list of values based on a filter:
data = %{
users: [
%{
id: 1,
name: "Alice",
friends: [
%{id: 1, name: "Barry"},
%{id: 2, name: "Bob"},
%{id: 3, name: "Charlie"}
]
}
]
}
# Get the ids of the friends with a "B" in their name
ids = get_in(data, [
:users,
Access.at(0),
:friends,
Access.filter(&(String.contains?(&1.name, "B"))),
:id
])
IO.inspect(ids) #=> [1, 2]
The end
More posts
Liveview
LiveView
Phoenix
Liveview
LiveView
Phoenix
Artificial Intelligence
Design
Application UI
Liveview
LiveView
Phoenix
Design
Component
Application UI
Liveview
LiveView
Phoenix
Design
Component
Liveview
LiveView
Phoenix
Component
Application UI