Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put key value pair into map with variable key name

Tags:

elixir

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.

like image 741
Dania_es Avatar asked Apr 24 '15 01:04

Dania_es


People also ask

What is a key value pair in a map?

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.

What are sets and maps in JavaScript?

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.


1 Answers

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)
like image 83
José Valim Avatar answered Oct 27 '22 06:10

José Valim