我有以下数组
array = [{
key: '2001',
values: [
{ id : '123a', points: 3, hours: 3 },
{ id : '123a', points: 4, hours: 2 },
{ id : '4444', points: 3, hours: 2 },
{ id : '4444', points: 3, hours: 5 },
]
}, {
key: '2002',
values: [
{ id : '12d3a', points: 5, hours: 2 },
{ id : '12w3a', points: 3, hours: 3 },
]
}]
使用此功能
const {map, evolve, pipe, groupBy, prop, pluck, sum, toPairs, zipObj} = R;
const a = map(evolve({
values: pipe(
groupBy(prop('id')),
map(pluck('hours')),
map(sum),
toPairs,
map(zipObj(['id', 'hours']))
)
}))
我收集了所有"小时"每个密钥的每个id(2001,2002 ..)
array = [{
key: '2001',
values: [
{ id : '123a', hours: 5 },
{ id : '4444', hours: 7 }....
现在我想为每个对象添加另一个值,称为sum。 var sum =(points * hours)/(sum(hours))。
知道我该怎么办?我试图更改const a但是没有工作,我不知道ramda是否可以进行此操作。也许另类?
array = [{
key: '2001',
values: [
{ id : '123a', hours: 5, sum: 3.4 },
{ id : '4444', hours: 7, sum: 3 }....
答案 0 :(得分:1)
这是一个Ramda版本,通过缩减为具有id,总小时数和总分数的中间结构,然后转换为最终格式:
const {map, evolve, pipe, groupBy, prop, reduce, values} = R;
const array = [{"key": "2001", "values": [{"hours": 3, "id": "123a", "points": 3}, {"hours": 2, "id": "123a", "points": 4}, {"hours": 2, "id": "4444", "points": 3}, {"hours": 5, "id": "4444", "points": 3}]}, {"key": "2002", "values": [{"hours": 2, "id": "12d3a", "points": 5}, {"hours": 3, "id": "12w3a", "points": 3}]}]
const a = map(evolve({
values: pipe(
groupBy(prop('id')),
map(reduce(
({tp, th}, {id, points, hours}) => ({id, tp: tp + points * hours, th: th + hours})
, {tp: 0, th: 0}
)),
values,
map(({id, th, tp}) => ({id, hours: th, sum: tp/th})),
)
}))
console.log(a(array))

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
&#13;
答案 1 :(得分:0)
尝试以下
var array = [{
key: '2001',
values: [
{ id : '123a', points: 3, hours: 3 },
{ id : '123a', points: 4, hours: 2 },
{ id : '4444', points: 3, hours: 2 },
{ id : '4444', points: 3, hours: 5 },
]
}, {
key: '2002',
values: [
{ id : '12d3a', points: 5, hours: 2 },
{ id : '12w3a', points: 3, hours: 3 },
]
}];
array.forEach((item) => {
var map = {};
item.values.forEach((obj) => {
map[obj.id] = map[obj.id] || [];
map[obj.id].push(obj);
});
var values = [];
Object.values(map).forEach((vals) => {
var n = 0, d = 0;
vals.forEach((val) => {
n += val.points * val.hours;
d += val.hours;
});
values.push({
'id' : vals[0].id,
'hours' : d,
'sum' : n/d
});
});
item.values = values;
});
console.log(array);
&#13;
您也可以尝试遵循逻辑
array.forEach((item) => {
var map = {};
item.values.forEach((obj) => {
map[obj.id] = map[obj.id] || {id : obj.id, n: 0, hours: 0};
map[obj.id].hours += obj.hours;
map[obj.id].n += (obj.points * obj.hours);
});
var values = Object.values(map);
values.forEach((val) => {
val.sum = val.n / val.hours;
delete val.n;
});
item.values = values;
});