按键值对分组,同时使用ramda合并重复项

时间:2019-03-16 21:30:43

标签: javascript ramda.js

我有一系列形式错误,如下所示:

[
  {
    "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函数实现此目标的最佳选择是什么?

1 个答案:

答案 0 :(得分:3)

使用R.pipe(或R.compose)创建按path属性(通过R.prop)分组的函数,然后在{内使用R.pluck {1}}以获得每个组中的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)