我在Ramda中编写了一个映射器,该映射器简化了对象并删除了具有空数组的属性。这是一件非常简单的事情,但是当我研究该函数时,我不得不组合在一起的Ramda辅助方法会使我在数周的时间内挠头。

我想知道是否有一种更干净的方法来达到相同的结果。

这是代码:

const filters = {
  Brand: [],
  BusinessUnit: [
    {
      FilterName: 'BusinessUnit',
      KeyItem: 'Beauty'
    },
    {
      FilterName: 'BusinessUnit',
      KeyItem: 'Sports'
    }
  ],
  Category: [],
  SKU: [
    {
      FilterName: 'SKU',
      KeyItem: '9023'
    }
  ]
}

const expectedFilters = {
  BusinessUnit: ['Beauty', 'Sports'],
  SKU: ['9023']
};

///////////////////////////////////////////////
// is there any way to write it cleaner

const result = R.compose(
  R.pickBy(R.pipe(R.isEmpty, R.not)),
  R.map(R.map(R.prop('KeyItem')))
)(filters);

///////////////////////////////////////////////

console.log('(expectedFilters:: ', expectedFilters);
console.log('result:: ', result);
console.log('is equal? ', R.equals(expectedFilters, result)); // true


这是此代码在Stackblitz上运行的链接。

最佳答案

更新资料

@codepic指出,使用reject代替组合filtercomplement仍然更好。这显然是一种优越的解决方案:



const transform = pipe (
  reject (isEmpty),
  map (pluck ('KeyItem') )
)

const filters = {Brand: [], BusinessUnit: [{FilterName: 'BusinessUnit', KeyItem: 'Beauty'}, {FilterName: 'BusinessUnit', KeyItem: 'Sports'}], Category: [], SKU: [{FilterName: 'SKU', KeyItem: '9023'}]}

console .log (
  transform (filters)
)

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
<script> const {pipe, reject, isEmpty, map, pluck} = R   </script>





原始答案

肯定有一些清理工作。我认为complement (isEmpty)pipe (isEmpty, not)干净得多。而map (prop ('foo') )具有内置功能pluck ('foo')。尽管pickBy可以正常工作,但由于filter可以覆盖对象和数组,因此它在一段时间前就变得多余了。

所以我的(现在已经过时的)版本看起来像这样:



const transform = pipe (
  filter (complement (isEmpty) )
  map (pluck ('KeyItem') )
)

const filters = {Brand: [], BusinessUnit: [{FilterName: 'BusinessUnit', KeyItem: 'Beauty'}, {FilterName: 'BusinessUnit', KeyItem: 'Sports'}], Category: [], SKU: [{FilterName: 'SKU', KeyItem: '9023'}]}

console .log (
  transform (filters)
)

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
<script> const {pipe, filter, complement, isEmpty, map, pluck} = R   </script>





当然,要为将complement (isEmpty)提取为notEmpty并可能将filter (notEmpty)提取为类似removeEmpties之类的参数。显然,这些都是容易做到的。

09-18 02:20