Lodash uniqBy调用的Ramda等效项是什么?

时间:2019-05-09 00:15:59

标签: javascript arrays object ecmascript-6 ramda.js

const data = [
{id: "001", failedReason: [1000]},
{id: "001", failedReason: [1001]},
{id: "001", failedReason: [1002]},
{id: "001", failedReason: [1000]},
{id: "001", failedReason: [1000, 1003]},
{id: "002", failedReason: [1000]}
];

如果仅想返回具有唯一id值的对象数组,则给出此数据集,那么我可以使用Lodash来简单地调用: _.uniqBy(data, 'id')

我知道,使用这种方法,只会保留第一次出现的元素/匹配项。

以上内容将返回:

[ { id: '001', failedReason: [ 1000 ] },
  { id: '002', failedReason: [ 1000 ] } ]

我是Ramda的新手。 Ramda单衬板相当于什么?

R.uniqBy(???, data)

2 个答案:

答案 0 :(得分:1)

只需返回每个元素的id

const data = [
{id: "001", failedReason: [1000]},
{id: "001", failedReason: [1001]},
{id: "001", failedReason: [1002]},
{id: "001", failedReason: [1000]},
{id: "001", failedReason: [1000, 1003]},
{id: "002", failedReason: [1000]}
];
const res = R.uniqBy(({ id }) => id, data);
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

您还可以使用Ramda prop函数:

const data = [
{id: "001", failedReason: [1000]},
{id: "001", failedReason: [1001]},
{id: "001", failedReason: [1002]},
{id: "001", failedReason: [1000]},
{id: "001", failedReason: [1000, 1003]},
{id: "002", failedReason: [1000]}
];
const res = R.uniqBy(R.prop("id"), data);
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

答案 1 :(得分:1)

Ramda并没有采用lodash的样式,即允许字符串充当函数的替代方法来获取对象的命名属性。因此,只需传递一个函数:

const data = [
  {id: "001", failedReason: [1000]},
  {id: "001", failedReason: [1001]},
  {id: "001", failedReason: [1002]},
  {id: "001", failedReason: [1000]},
  {id: "001", failedReason: [1000, 1003]},
  {id: "002", failedReason: [1000]}
];

console.log(uniqBy(prop('id'), data))
<script src="https://bundle.run/ramda@0.26.1"></script><script>
const {uniqBy, prop} = ramda    </script>