How do I return only the nested list element in orders with :id matching 127? How do I search for it within the list, "orders", without knowing it's position (just searching by value)?
orders
[[id: 123, ship_to: :NC, net_amount: 100.0],
[id: 124, ship_to: :OK, net_amount: 35.5],
[id: 125, ship_to: :TX, net_amount: 24.0],
[id: 126, ship_to: :TX, net_amount: 44.8],
[id: 127, ship_to: :NC, net_amount: 25.0],
[id: 128, ship_to: :MA, net_amount: 10.0],
[id: 129, ship_to: :CA, net_amount: 102.0],
[id: 139, ship_to: :NC, net_amount: 50.0]]
Desired result: [id: 127, ship_to: ...]
You can use Enum.find/2
for this. It takes an enumerable (like the orders
list you have here) and a function and returns the first element for which the function returns a truthy value (non- false
and non- nil
).
Enum.find(orders, fn order -> {:id, 127} in order end)
This is just one possible solution; there are many possible ones :). For example, you could use the []
syntax with Enum.find/2
as well:
Enum.find(orders, fn order -> order[:id] == 127 end)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.