Ramda GroupBy-如何按道具分组

时间:2019-06-18 10:06:41

标签: javascript functional-programming ramda.js

给定:

interface Dict {
  [key: string]: any
}

const data: Dict[] = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' },  
];

未指定这些Dict对象的键...

如何获得此结果?

const result = {
  id: ['a', 'b', 'c', 'd', 'e'],
  b: ['something', 'else'],
  extra: ['hello world'],
  // ... and any other possible key
}

3 个答案:

答案 0 :(得分:4)

您可以将对象展平为成对的列表,将其分组,然后将对转换回值:

const data = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' },  
];


let z = R.pipe(
  R.chain(R.toPairs),
  R.groupBy(R.head),
  R.map(R.map(R.last))
)

console.log(z(data))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

答案 1 :(得分:3)

Ori Drori的答案略有不同: (假设对象中的属性已经不包含在数组中)

const data = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' }
];

const run = reduce(useWith(mergeWith(concat), [identity, map(of)]), {});

console.log(
  run(data)
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
<script>const {reduce, useWith, mergeWith, concat, identity, map, of} = R;</script>

答案 2 :(得分:2)

将R.reduce与R.mergeWith一起使用并合并所有项目:

const { mergeWith, reduce } = R

const fn = reduce(mergeWith((a, b) => [].concat(a, b)), {})


const data = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' },  
];

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

如果您还需要数组中的单个值(extra),请映射项目并包装成一个数组,仅包含尚未是数组的值:

const { pipe, mergeWith, reduce, map, unless, is, of } = R

const fn = pipe(
  reduce(mergeWith((a, b) => [].concat(a, b)), {}),
  map(unless(is(Array), of))
)


const data = [
  { id: 'a' },
  { id: 'b', b: 'something' },
  { id: 'c', b: 'else' },  
  { id: 'd', extra: 'hello world' },
  { id: 'e' },
];

const result = fn(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>