Reputation: 975
I have an array of form errors that look like this:
[
{
"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",
}
]
The shape needs to be transformed so that it fits the form’s error API. What I’d like to do is to transform it using ramda so that it ends up like this:
{
email: ["email must be at least 10 characters", "email must be a valid email"],
password: ["password must be at least 8 characters"]
}
What would be the best choice of ramda functions to use to achieve this?
Upvotes: 1
Views: 168
Reputation: 191976
Use R.pipe
(or R.compose
) to create a function that groups by the path
property (via R.prop
), and then uses R.pluck
inside R.map
to get the message
properties in each group:
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>
Upvotes: 3