项目作者: treble37

项目描述 :
Providing Map#drop (by key or value) and Map#take functionality for nested maps
高级语言: Elixir
项目地址: git://github.com/treble37/nested_filter.git
创建时间: 2017-03-22T03:43:44Z
项目社区:https://github.com/treble37/nested_filter

开源协议:MIT License

下载


NestedFilter

Build
Maintainability
Test Coverage
Coverage Status
Hex.pm
Hex.pm Downloads
GitHub stars
GitHub license

The Problems

  1. You have a nested map (or a struct that you converted to a nested map) and you want to remove ALL the keys with specific values such as nil.
  2. You want to do a Map#take on a nested map
Example: Remove all the map keys with nil values
  1. nested_map = %{a: 1, b: %{c: nil, d: nil}, c: nil}
  2. Map.drop(nested_map, [:c, :d])
  3. # => %{a: 1, b: %{c: nil, d: nil}}
  4. # But you actually wanted:
  5. # => %{a: 1}

The Solution: NestedFilter

NestedFilter drills down into a nested map and can do any of the following:

  1. filters out keys according to user specified values.
  2. filters out values according to user specified keys.

Installation

If available in Hex, the package can be installed
by adding nested_filter to your list of dependencies in mix.exs:

  1. def deps do
  2. [{:nested_filter, "~> 1.2.2"}]
  3. end

Documentation can be generated with ExDoc
and published on HexDocs. Once published, the docs can
be found at https://hexdocs.pm/nested_filter.

Usage

By default, when removing user specified values, empty values will be preserved
(see Case 1 below). You can add empty values to the user specified values list
if you wish those “empty values” (e.g., empty maps) to be removed.

NestedFilter.drop_by_value

  1. # Case 1: Remove the nil values from a nested map, preserving empty map values
  2. nested_map = %{a: 1, b: %{m: nil, n: 2}, c: %{p: %{q: nil, r: nil}, s: %{t: 2, u: 3}} }
  3. NestedFilter.drop_by_value(nested_map, [nil])
  4. # => %{a: 1, b: %{n: 2}, c: %{p: %{}, s: %{t: 2, u: 3}} }
  5. # Case 2: Remove the nil values from a nested map, removing empty map values
  6. nested_map = %{a: 1, b: %{m: nil, n: 2}, c: %{p: %{q: nil, r: nil}, s: %{t: 2, u: 3}} }
  7. NestedFilter.drop_by_value(nested_map, [nil, %{}])
  8. # => %{a: 1, b: %{n: 2}, c: %{s: %{t: 2, u: 3}} }

NestedFilter.drop_by_key

  1. # Case 1: Remove values from a nested map by key
  2. nested_map = %{a: 1, b: %{a: 2, b: 3}, c: %{a: %{a: 1, b: 2}, b: 2, c: %{d: 1, e: 2}}}
  3. assert NestedFilter.drop_by_key(nested_map, [:a]) == %{b: %{b: 3},c: %{b: 2, c: %{d: 1, e: 2}}}

NestedFilter.take_by_key

  1. # Case 1: Take values from a nested map by key
  2. nested_map = %{a: %{b: 1}, c: 3, e: %{f: 4}}
  3. assert NestedFilter.take_by_key(nested_map, [:b, :f]) == %{b: 1, f: 4 }

You can browse the tests for more usage examples.