我有一个动态创建的 map 数据结构,稍后将被解析为 JSON。因此嵌套级别等是未知的并且取决于数据。
如果一个键有多个值,它们将表示为序列中的映射。
这是一个例子:
{:key "value"
:anotherKey "anotherValue"
:foo "test"
:others [ {:foo "test2"} {:foo "test3"} ]
:deeper {:nesting {:foo "test4"} }
}
我现在想搜索键 :foo
并将 "/bar"
附加到值。
结果应该返回修改后的 map :
{:key "value"
:anotherKey "anotherValue"
:foo "test/bar"
:others [ {:foo "test2/bar"} {:foo "test3/bar"} ]
:deeper {:nesting {:foo "test4/bar"} }
}
实现该目标的简洁方法是什么?
我尝试了一种递归方法,但除了大型数据结构的内存问题之外,我还在努力返回附加值。
最佳答案
可能有比这更简单的东西:
(clojure.walk/prewalk
(fn [m]
(if (and (map? m) (:foo m))
(update-in m [:foo] #(str % "/bar"))
m))
{:key "value"
:anotherKey "anotherValue"
:foo "test"
:others [{:foo "test2"} {:foo "test3"}]
:deeper {:nesting {:foo "test4"}}})
=>
{:anotherKey "anotherValue",
:key "value",
:deeper {:nesting {:foo "test4/bar"}},
:foo "test/bar",
:others [{:foo "test2/bar"} {:foo "test3/bar"}]}
关于collections - Clojure:在动态嵌套映射/序列中搜索/替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28965549/