I have a list of maps that provide a type of property lookup, and a map with values.
lookup =
[
%{key: "foo", type: :string},
%{key: "bar", type: :string},
%{key: "baz", type: :string}
]
params = %{foo: "bananas", baz: "apples}
What I’ve been attempting to do (unsuccessfully) is to use Enum.reduce
, for lack of a better approach, in order to combine the two into the following format, while discarding any lookup keys that aren’t present in values:
output =
[
%{key: :foo, value: "bananas", type: :string},
%{key: :baz, value: "apples", type: :string},
]
I had tried this, but I can’t work out how to access the value from params using the atom key from lookup.
def clever_merge(lookup, params) do
Enum.reduce(lookup, [], fn(%{key: k, type: t}, output) ->
with rec <- %{key: String.to_atom(k), value: params.k, type: t} do
List.insert_at(output, -1, rec)
end
end)
end
The other issue is filtering out keys that aren’t present in params. I tried a few combinations of if statements around Enum.reduce but I couldn’t work it out.
I know it’s always a big ask but could someone point me in the right direction please?
Thanks.