Get the value from map within list

[
 %Component{
    allocated_quantity: 3,
    component_handle: "dd",
    component_id: 11,
    pricing_scheme: "per_unit",
    subscription_id: 111,
  }
]

I have a map within list, I want to get the value of allocated_quantity, just as an integer.
without any [] or {}…
how can I get this??

There is get_in or pattern matching. The last being really important in Elixir. It is one of the tool You need to start using…

Please try first, and come back if You don’t get it :slight_smile:

1 Like

Given:

defmodule Component do
  defstruct [
    :allocated_quantity,
    :component_handle,
    :component_id,
    :pricing_scheme,
    :subscription_id
  ]
end

x = [
 %Component{
    allocated_quantity: 3,
    component_handle: "dd",
    component_id: 11,
    pricing_scheme: "per_unit",
    subscription_id: 111,
  }
]

This works

x |> Enum.at(0) |> get_in([Access.key(:allocated_quantity)])

This won’t works

x |> Enum.at(0) |> get_in([:allocated_quantity])

Or a simple pattern match.

[%{allocated_quantity: aq}] = x
4 Likes

You haven’t understood Access:

x = [%{a: 1, b: 2}]
get_in(x, [Access.at(0), Access.key(:b)])

Yields 2 as it should.

But it’s very convoluted to access data that way. Pattern-matching is much faster and clearer to write. Using Access is justified when the shape of the data isn’t suited for pattern-matching (like when you don’t know the list size beforehand).

2 Likes