Ramda JS groupBy和transform对象

问题描述 投票:0回答:1

我想使用RamdaJS转换这个对象数组。从这个对象数组

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" }
]

进入这个对象数组

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 }
    ]
  }
]

这是我到目前为止所做的。但我没能从孩子的阵列中删除父键

R.pipe(
  R.groupBy(R.prop('father')),
  R.map(kids => ({ 
    father: R.head(kids)["father"],
    count: kids.length,
    kids: kids
  })),
  R.values()
)(children)
ramda.js
1个回答
2
投票

使用R.applySpec创建对象,并使用R.map和R.dissoc删除'father'属性:

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>
© www.soinside.com 2019 - 2024. All rights reserved.