How to fetch out the value from a this complex list?

How to fetch out the “id” value from the following piece of code when I have a string for which I have to match with each value key by the substring matching.
for ex- String I have saasgasgasdaaaaacricketintelligento. Now, I want to match each value from the Value key, if present then return id key's value else nil.

[
   %{"id" => 1, "value" => ["intelligent", "software dev"]},
   %{"id" => 2, "value" => ["cricket", "job1"]},
   %{"id" => 3, "value" => ["cricket", "job1"]},
   %{"id" => 4, "value" => ["cricket", "khokho", "game developer"]}
 ]

I’m not quite sure I fully understand what you mean, but this should work to extract an id based on a partial match of the concatenated elements in the value list of each entry:

[
  %{"id" => 1, "value" => ["intelligent", "software dev"]},
  %{"id" => 2, "value" => ["cricket", "job1"]},
  %{"id" => 3, "value" => ["cricket", "job1"]},
  %{"id" => 4, "value" => ["cricket", "khokho", "game developer"]}
]
|> Enum.find(fn %{"value" => value} ->
  value
  |> Enum.reduce("", fn element, acc -> element <> acc end)
  |> String.contains?("cricket")
end)
|> Map.get("id")
|> IO.inspect()
# prints 2

Because of the string concatenation involved it is not the most efficient solution, probably. I would recommend, however, to refactor your data structure into a map first, instead of a list of maps. Why not use something like %{"1" => ["intelligent", "software dev"]}?

1 Like

It should be acc || (entry |> ...) or you will effectively only compare the last value in the list.

@ycv005, can you write a function, that identifies a single map as a map or not match?

1 Like