简体   繁体   English

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

[英]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. 需要对形状进行转换,使其符合表单的错误API。 What I'd like to do is to transform it using ramda so that it ends up like this: 我想做的是使用ramda对其进行转换,使其最终结果如下:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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