简体   繁体   中英

Group by key value pairs whilst merging duplicates using ramda

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM