I'm trying to end up with a single map containing many different preferences, it should look like this:
%{some_preference_name:%{foo:"bar"},another_preference_name:%{foo:"bar"}}
I have a list of preference maps from the database, and I need to get through them and set the "preference" field as the key with the various values as the values map.
I tried to do this with Enum.reduce and Enum,map, but I can't get the list right.
Enum.map(preferences, fn(data)->
Map.put(%{}, data.preference,
%{
foo: data.foo
}
)
end)
returns:
[{some_preference_name:%{foo:"bar"}},{another_preference_name:%{foo:"bar"}}]
then:
Enum.reduce(preferences, fn(acc, data)->
Map.put(acc, data.preference,
%{
foo: data.foo
}
)
end)
returns:
%{some_preference_name:%{foo:"bar"},preference: "another_preference_name",foo:"bar"}
It gets the first one right, but not the rest. I understand that as of Erlang R17, the only way I will be able to add a variable key name is with Map.put/3.
A Map object associates or maps one set of values, called keys, to another set of values. A key and the value it is mapped to are known as a key-value pair. A map can contain any number of key-value pairs, but each key must be unique. A key may be any Integer, object reference or null-terminated String.
Developers use Objects to store key/value pairs and Arrays to store indexed lists. However, to give developers more flexibility, the ECMAScript 2015 specification introduced two new types of iterable objects: Maps, which are ordered collections of key/value pairs, and Sets, which are collections of unique values.
Your code is almost correct, you have just swapped the arguments order in the reduce function:
Enum.reduce(preferences, fn(data, acc)->
Map.put(acc, data.preference, %{foo: data.foo})
end)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With