使用ramda转换对象中包含重复项的数组
var testData = [
{"id" : "001",
"project" : "one",
"projectstartDate" : "10/12/2018"
},{"id" : "001",
"project" : "two",
"projectstartDate" : "10/14/2018"
},{"id" : "002",
"project" : "one",
"projectstartDate" : "10/12/2018"
},{"id" : "002",
"project" : "two",
"projectstartDate" : "10/14/2018"
}
]
{
"001" : {
"one" : {
"projectstartDate" : "10/12/2018"
},
"two" : {
"projectstartDate" : "10/14/2018"
}
},
"002" :{
"one" : {
"projectstartDate" : "10/12/2018"
},
"two" : {
"projectstartDate" : "10/14/2018"
}
}
创建以id为键的对象并删除重复项
答案 0 :(得分:1)
我们将其分解为几个步骤。
首先,当您具有要通过某种功能组合在一起的事物的列表时,类似R.groupBy
的内容可能会有所帮助。在此特定实例中,您想按id
属性分组,因此R.prop('id')
可以用作赋予R.groupBy
的函数。
const testData = [
{"id" : "001",
"project" : "one",
"projectstartDate" : "10/12/2018"
},{"id" : "001",
"project" : "two",
"projectstartDate" : "10/14/2018"
},{"id" : "002",
"project" : "one",
"projectstartDate" : "10/12/2018"
},{"id" : "002",
"project" : "two",
"projectstartDate" : "10/14/2018"
}
]
console.log(R.groupBy(R.prop('id'), testData))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
将这些分组后,您希望在按某个值索引的对象中转换列表,这通常是达到R.indexBy
的好时机。因为我们要索引与每个分组对象的键关联的每个列表,所以我们需要在对象上R.map
。
const testData = {
"001": [
{
"id": "001",
"project": "one",
"projectstartDate": "10/12/2018"
},
{
"id": "001",
"project": "two",
"projectstartDate": "10/14/2018"
}
],
"002": [
{
"id": "002",
"project": "one",
"projectstartDate": "10/12/2018"
},
{
"id": "002",
"project": "two",
"projectstartDate": "10/14/2018"
}
]
}
console.log(
R.map(R.indexBy(R.prop('project')), testData)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
然后,我们必须清除嵌套对象中剩余的剩余属性。您在此处有几个选择,即通过声明要使用R.omit
删除的属性或要使用R.pick
保留的属性。
const testData = {
"id" : "001",
"project" : "one",
"projectstartDate" : "10/12/2018"
}
console.log(
R.pick(['projectstartDate'], testData)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
现在剩下的就是使用R.pipe
和R.map
通过管道将其全部连接起来。
const testData = [
{"id" : "001",
"project" : "one",
"projectstartDate" : "10/12/2018"
},{"id" : "001",
"project" : "two",
"projectstartDate" : "10/14/2018"
},{"id" : "002",
"project" : "one",
"projectstartDate" : "10/12/2018"
},{"id" : "002",
"project" : "two",
"projectstartDate" : "10/14/2018"
}
]
const fn = R.pipe(
R.groupBy(R.prop('id')),
R.map(R.pipe(
R.indexBy(R.prop('project')),
R.map(R.pick(['projectstartDate']))
))
)
console.log(
fn(testData)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>