-->

RamdaJS groupBy and tranform object

2019-08-20 09:52发布

问题:

I want to transform this array of objects using RamdaJS. From this array of objects

let children = [
  { "name": "Bob", "age": 8, "father": "Mike" },
  { "name": "David", "age": 10, "father": "Mike" },
  { "name": "Amy", "age": 2, "father": "Mike" },
  { "name": "Jeff", "age": 11, "father": "Jack" }
]

into this array of objects

let fatherAndKids = [
  {
    "father": "Mike",
    "count" : 3,
    "kids": [
      { "name": "Bob", "age": 8 },
      { "name": "David", "age": 10 },
      { "name": "Amy", "age": 2
      }
    ]
  },
  {
    "father": "Jack",
    "count" : 1,
    "kids": [
      { "name": "Jeff", "age": 11 }
    ]
  }
]

Here's what i did so far. But i failed to remove the father keys from kids's array

R.pipe(
  R.groupBy(R.prop('father')),
  R.map(kids => ({ 
    father: R.head(kids)["father"],
    count: kids.length,
    kids: kids
  })),
  R.values()
)(children)

回答1:

Use R.applySpec to create the object, and use R.map with R.dissoc to remove the 'father' property:

const { pipe, groupBy, prop, applySpec, head, length, map, dissoc, values } = R

const fn = pipe(
  groupBy(prop('father')),
  map(applySpec({
    father: pipe(head, prop('father')),
    count: length,
    kids: map(dissoc('father'))
  })),
  values
)

const children = [
  { "name": "Bob", "age": 8, "father": "Mike" },
  { "name": "David", "age": 10, "father": "Mike" },
  { "name": "Amy", "age": 2, "father": "Mike" },
  { "name": "Jeff", "age": 11, "father": "Jack" }
]

const result = fn(children)

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



标签: ramda.js