shahryarjb

shahryarjb

Nested list of maps add or update another nested key

I have a nested list that should follow a rules to update a record or add a record.
I have a keys list which is the path I need to update or add

Entry list

[
      %{
        name: :actor,
        opts: [
          struct: MishkaDeveloperToolsTest.GuardedStruct.NestedConditionalFieldTest.Actor,
          derive: "validate(map, not_empty)",
          hint: "001-1-map",
          validator: {ConditionalFieldValidatorTestValidators, :is_map_data},
          __tag__: "root"
        ]
      },
      %{
        name: :actor,
        opts: [
          derive: "sanitize(tag=strip_tags) validate(url, max_len=160)",
          hint: "001-2-url",
          validator: {ConditionalFieldValidatorTestValidators, :is_string_data},
          __tag__: "root"
        ]
      }
    ]

For example I have a keys list like this ["root", "aa"], and I want to add new record to the list

  1. I need to find is there a list that has __tag__: "root::aa" if not add another map to bottom of the list
  2. if it can be found, I need add a map inside fields key

When can not find

[
      %{
        name: :actor,
        opts: [
          struct: MishkaDeveloperToolsTest.GuardedStruct.NestedConditionalFieldTest.Actor,
          derive: "validate(map, not_empty)",
          hint: "001-1-map",
          validator: {ConditionalFieldValidatorTestValidators, :is_map_data},
          __tag__: "root"
        ]
      },
      %{
        name: :actor,
        opts: [
          derive: "sanitize(tag=strip_tags) validate(url, max_len=160)",
          hint: "001-2-url",
          validator: {ConditionalFieldValidatorTestValidators, :is_string_data},
          __tag__: "root"
        ]
      },
     // add new map last of the list
     %{
        name: :actor,
        opts: [
          derive: "sanitize(tag=strip_tags) validate(url, max_len=160)",
          hint: "001-2-url",
          validator: {ConditionalFieldValidatorTestValidators, :is_string_data},
          __tag__: "root:aa"
        ]
      }
    ]

When we find it

[
  %{
    name: :actor,
    opts: [
      struct: MishkaDeveloperToolsTest.GuardedStruct.NestedConditionalFieldTest.Actor,
      derive: "validate(map, not_empty)",
      hint: "001-1-map",
      validator: {ConditionalFieldValidatorTestValidators, :is_map_data},
      __tag__: "root"
    ]
  },
  %{
    name: :actor,
    opts: [
      derive: "sanitize(tag=strip_tags) validate(url, max_len=160)",
      hint: "001-2-url",
      validator: {ConditionalFieldValidatorTestValidators, :is_string_data},
      __tag__: "root"
    ]
  },
  %{
    name: :actor,
    opts: [
      derive: "sanitize(tag=strip_tags) validate(url, max_len=160)",
      hint: "001-2-url",
      validator: {ConditionalFieldValidatorTestValidators, :is_string_data},
      __tag__: "root:aa"
    ],
    // add the map inside fields
    fields: [
      %{
        name: :actor,
        opts: [
          derive: "sanitize(tag=strip_tags) validate(url, max_len=160)",
          hint: "001-2-url",
          validator: {ConditionalFieldValidatorTestValidators, :is_string_data},
          __tag__: "root:aa"
        ]
      }
    ]
  }
]

As you see I added it inside the last map and add fields keys.


It should be noted the path keys can have 3 or 4 etc items and my code needs to implement none-limit nested map. for example:

 __tag__: "root:aa::bb::cc::gg"
["root", "aa", "bb", "cc", "gg"]

Thank you very much for your guidance

First Post!

gpopides

gpopides

defmodule E do
  def foo(record, keys, list) do
    key = Enum.join(keys, "::")

    # a function that extracts the key from the record 
    record_key = fn record ->
      record.opts[:__tag__]
    end

    assign_key = fn record ->
      %{record | opts: Keyword.replace(record.opts, :__tag__, key)}
    end

    Enum.group_by(list, record_key)
    |> Map.update(key, record, fn existing_record ->
      existing_record[:fields] = [record | existing_record[:fields]]
    end)
    |> Map.values()
  end
end

You can use something like this. Probably its not 100% correct but the idea is there.

  1. construct the key from the list
  2. Convert the list to a map using the key you want to check if it exists
  3. Use Map.update/4 to update the record with the given key. If it exists, you push the record to the fields field. If not you assign the record as a value of the map
  4. Convert back to a list to get the same structure you had as input
  5. use assign_key to set the records tag to the join key constructed from the list.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New

Other popular topics Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement