RamdaJS groupBy 和转换对象 [英] RamdaJS groupBy and tranform object

查看:35
本文介绍了RamdaJS groupBy 和转换对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

进入这个对象数组

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

这是我到目前为止所做的.但是我没有从孩子的数组中删除 father

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)

推荐答案

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

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>

这篇关于RamdaJS groupBy 和转换对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆