collections - Clojure:在动态嵌套映射/序列中搜索/替换值

标签 collections clojure

我有一个动态创建的 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/

相关文章:

c# - Microsoft 会让 LINQ 可以使用所有集合吗?

c# - 拼接系列

c# - 将 arraylist 对象写入文件和从文件读取

java - 为什么使用 ArrayList 的 Collections.copy 会产生 IndexOutOfBounds 异常?

clojure - 运行lein-rpm任务时没有实现方法错误

java - 无法让 ant 工作,尝试安装 Clojure

list - clojure 尾递归中的 java.lang.StackOverflowError

java - Java8中可以通过流给object中的变量赋值吗?

clojure - 如何对 HashMap 中的所有值求和?

Clojure:incanter.stats 线性回归模型不起作用