[英]Reduce Array of Array of Objects Using Ramda
I have an array of array of objects.我有一组对象数组。 I want to reduce that to an array of object and adding one more property to each object.
我想将其减少为 object 数组,并为每个 object 添加一个属性。 The sample input is:
样本输入为:
const data = [
[
{name:"a", val:5},
{name:"b", val:10},
{name:"c", val:20},
{name:"d", val:50},
{name:"e", val:100}
],
[
{name:"a", val:0},
{name:"b", val:20},
{name:"c", val:30},
{name:"d", val:40},
{name:"e", val:10}
],
[
{name:"a", val:60},
{name:"b", val:50},
{name:"c", val:40},
{name:"d", val:70},
{name:"e", val:30}
]
];
And the Output should be: Output 应该是:
[{name: 'a', val: 65, rank: 'si'},
{name: 'b', val: 80, rank: 'dp'},
{name: 'c', val: 90, rank: 'en'}
{name: 'd', val: 160, rank: 'fr'}]
Rank
is static text means for a
, it will always be "si"
How can I achieve this using ramda ? Rank
是 static 文本表示a
,它总是"si"
我怎样才能使用ramda实现这一点?
You can convert flatten all sub arrays to a single array, group by the name
, and then map the groups, and reduce each group to a single object using R.mergeWithKey to add the val
property. You can convert flatten all sub arrays to a single array, group by the
name
, and then map the groups, and reduce each group to a single object using R.mergeWithKey to add the val
property. Convert back to an array using R.values, and map to add the static ranks property by name
.使用 R.values 和 map 转换回数组,以按
name
添加 static 等级属性。
Note that you must create a Map or a dictionary object to take the rank by name
from.请注意,您必须创建 Map 或字典 object 才能按
name
获取排名。
const { mergeWithKey, pipe, flatten, groupBy, prop, map, reduce, values } = R const ranks = new Map([['a', 'si'], ['b', 'dp'], ['c', 'en'], ['d', 'fr']]) // merge deep and combine val property values const combine = mergeWithKey((k, l, r) => k == 'val'? l + r: r) const mergeData = pipe( flatten, // flatten to a single array groupBy(prop('name')), // group by the name map(reduce(combine, {})), // combine each group to a single object values, // convert back to array map(o => ({...o, rank: ranks.get(o.name) })), // add the static rank property ) const data = [[{"name":"a","val":5},{"name":"b","val":10},{"name":"c","val":20},{"name":"d","val":50},{"name":"e","val":100}],[{"name":"a","val":0},{"name":"b","val":20},{"name":"c","val":30},{"name":"d","val":40},{"name":"e","val":10}],[{"name":"a","val":60},{"name":"b","val":50},{"name":"c","val":40},{"name":"d","val":70},{"name":"e","val":30}]] const results = mergeData(data) console.log(results)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.