我有一系列看起来像这样的形式错误:

[
  {
    "path": "email",
    "message": "email must be at least 10 characters",
  },
  {
    "path": "email",
    "message": "email must be a valid email",
  },
  {
    "path": "password",
    "message": "password must be at least 8 characters",
  }
]


需要对形状进行转换,以使其适合表单的错误API。我想做的是使用ramda对其进行转换,使其最终如下所示:

{
  email: ["email must be at least 10 characters", "email must be a valid email"],
  password: ["password must be at least 8 characters"]
}


实现此目标的ramda函数的最佳选择是什么?

最佳答案

使用R.pipe(或R.compose)创建一个按path属性分组(通过R.prop)的函数,然后在R.pluck中使用R.map获取每个组中的message属性:



const { pipe, groupBy, prop, map, pluck } = R

const fn = pipe(
  groupBy(prop('path')),
  map(pluck('message'))
)

const data = [{"path":"email","message":"email must be at least 10 characters"},{"path":"email","message":"email must be a valid email"},{"path":"password","message":"password must be at least 8 characters"}]

const result = fn(data)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

关于javascript - 按键值对分组,同时使用ramda合并重复项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55201676/

10-09 21:15