我有一系列形式错误,如下所示:
[
{
"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函数实现此目标的最佳选择是什么?
答案 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)