什么是 clojure.core 相当于 lodash _.pluck
What is clojure.core equivalent of lodash _.pluck
Lodash _.pluck 这样做
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
_.pluck(users, 'user');
// → ['barney', 'fred']
好的是它也可以像这样深入:
var users = [
{ 'user': {name: 'barney'}, 'age': 36 },
{ 'user': {name: 'fred'}, 'age': 40 }
];
_.pluck(users, 'user.name');
// ["barney", "fred"]
在 Clojure 核心中是否有与此等价的东西?我的意思是,我可以很容易地创建一行,有点像这样
(defn pluck
[collection path]
(map #(get-in % path) collection))
并像这样使用它:
(def my-coll [{:a {:z 1}} {:a {:z 2}}])
(pluck my-coll [:a :z])
=> (1 2)
我只是想知道 Clojure 中是否已经包含这样的东西,但我忽略了它。
没有内置函数。您可以参考 clojure.core API reference and the cheatsheet 查找可用的内容。
我想说 Clojure 的语法足够轻巧,感觉结合使用 map
和像 get-in
.
这样的访问实用程序就足够了
这也证明了 Clojure 社区广泛采用的原则:提供大部分简单的默认值,让用户根据需要组合它们。有些人可能会争辩说 pluck
将迭代和查询混为一谈。
lodash
弃用了 _.pluck
函数,取而代之的是 _.map
。因此:
_.pluck(users, 'user')
现在
_.map(users, 'user')
我喜欢 lodash/fp
风格,它将迭代器放在集合前面
_.map('user', users)
您还可以免费获得 autocurry
_.map('user')(users)
最简单的方法是这样的:
(map #(:user %) users)
它将return列出'(36 40)
这里有一些简单的技巧:
(def my-coll [{:a {:z 1}} {:a {:z 2}}])
(map :a my-coll)
=> ({:z 1} {:z 2})
(map (comp :z :a) my-coll)
=> (1 2)
有效,因为关键字的行为也像一个函数。
lodash 中的这个函数现在称为 pick and I believe its closest equivalent in Clojure is select-keys。
Lodash _.pluck 这样做
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
_.pluck(users, 'user');
// → ['barney', 'fred']
好的是它也可以像这样深入:
var users = [
{ 'user': {name: 'barney'}, 'age': 36 },
{ 'user': {name: 'fred'}, 'age': 40 }
];
_.pluck(users, 'user.name');
// ["barney", "fred"]
在 Clojure 核心中是否有与此等价的东西?我的意思是,我可以很容易地创建一行,有点像这样
(defn pluck
[collection path]
(map #(get-in % path) collection))
并像这样使用它:
(def my-coll [{:a {:z 1}} {:a {:z 2}}])
(pluck my-coll [:a :z])
=> (1 2)
我只是想知道 Clojure 中是否已经包含这样的东西,但我忽略了它。
没有内置函数。您可以参考 clojure.core API reference and the cheatsheet 查找可用的内容。
我想说 Clojure 的语法足够轻巧,感觉结合使用 map
和像 get-in
.
这也证明了 Clojure 社区广泛采用的原则:提供大部分简单的默认值,让用户根据需要组合它们。有些人可能会争辩说 pluck
将迭代和查询混为一谈。
lodash
弃用了 _.pluck
函数,取而代之的是 _.map
。因此:
_.pluck(users, 'user')
现在
_.map(users, 'user')
我喜欢 lodash/fp
风格,它将迭代器放在集合前面
_.map('user', users)
您还可以免费获得 autocurry
_.map('user')(users)
最简单的方法是这样的:
(map #(:user %) users)
它将return列出'(36 40)
这里有一些简单的技巧:
(def my-coll [{:a {:z 1}} {:a {:z 2}}])
(map :a my-coll)
=> ({:z 1} {:z 2})
(map (comp :z :a) my-coll)
=> (1 2)
有效,因为关键字的行为也像一个函数。
lodash 中的这个函数现在称为 pick and I believe its closest equivalent in Clojure is select-keys。